C# Checking if an object can cast to another object fails?
c#, inheritance, reflection
Solution
When you have
class B { }
class D : B {}
then
typeof(B).IsAssignableFrom(typeof(D)) // true
typeof(D).IsAssignableFrom(typeof(B)) // false
I think you are trying the 2nd form, it's not totally clear.
The simplest answer might be to test:
(factory.GetDerivedObject() as SomeDerivedType) != null
After the Edit:
What you want to know is not if someObject is assignable to SomeProperty but if it is castable.
The basis would be:
bool ok = someProperty.PropertyType.IsInstanceOfType(someObject);
But this only handles inheritance.
Problem
I'm trying to check if an object can cast to a certain type using `IsAssignableFrom`. However I'm not getting the expected results... Am i missing something here? ``` //Works (= casts object) (SomeDerivedType)factory.GetDerivedObject(); //Fails (= returns false) typeof(SomeDerivedType).IsAssignableFrom(factory.GetDerivedObject().GetType()); ``` EDIT: The above example seems wrong and doesn't reflect my problem very well. I have a `DerivedType` object in code which is cast to `BaseType`: ``` BaseType someObject = Factory.GetItem(); //Actual type is DerivedType ``` I also have a `PropertyType` through reflection: ``` PropertyInfo someProperty = entity.GetType().GetProperties().First() ``` I would like to check if `someObject` is assignable to (castable to) the `PropertyType` of `someProperty`. How can I do this?