How to use variable type in as operator

1.3k Views Asked by At

For example:I have 2 variable (value ) & (property) i want to check is cast possible for value? We do not know the type of variables, How to check if cast is possible?

   var value = Reader[item];
   PropertyInfo property = properties.Where(x => x.Name == item).FirstOrDefault();
   var type=property.PropertyType;//Or property.ReflectedType
   var cs= value as type // Error: type is variable but is used like a Type
   if (cs!=null){
     ...
    }

Sample 1:

var value = 123;//is int
type = property.GetType();// is double
var x = (double)value;//Can be casted

Sample 2:

var value = "asd";//is string
type = property.GetType();// is double
var x = (double)value;//Can not be casted
2

There are 2 best solutions below

5
On

In your code snippet, type is a variable of type Type, hence why it is throwing that error. You can change your code to use Convert.ChangeType() instead. Something like this:

   var value = Reader[item];
   PropertyInfo property = properties.Where(x => x.Name == item).FirstOrDefault();
   var type=property.PropertyType;
   object cs= Convert.ChangeType(value, type);
   if (cs!=null){
     ...
    }

Notice that, since you don't know the strong type of your property at compile time, you still have to box it into an object type after changing its type. This means you wouldn't be able to access its properties and methods directly using dot syntax in code (e.g. cs.MyProperty). If you wish to be able to do that, you can use the dynamic type in C#:

dynamic dcs = cs;
Console.Write(dcs.MyProperty);

When using Convert.ChangeType() you have to make sure you are converting to the correct type. E.g.:

if (value.GetType() == type)
{
   object cs= Convert.ChangeType(value, type);   
}
1
On

You can use IsAssignable:

bool isValidCast = type.IsAssignableFrom(value.GetType())

As per the comments about int to double: I've made a mistake in my comment, so i deleted it. int can be implicitly converted to double because there is a predefined implicit conversion, see here

There are many ways to convert or cast from type to type. For example, You can use implicit/explicit conversion, you can use TypeConverter or implement the IConvertible interface.

Now, you have to decide which use case is relevant to you. It can be a bit complex to check them all, especially without knowing the destination type at design time.