C # Checking that an object can be transferred to another object?
I am trying to check if an object can be of a specific type using IsAssignableFrom
. However, I am not getting the expected results ... Am I missing something?
//Works (= casts object)
(SomeDerivedType)factory.GetDerivedObject();
//Fails (= returns false)
typeof(SomeDerivedType).IsAssignableFrom(factory.GetDerivedObject().GetType());
EDIT:
The above example seems to be wrong and doesn't reflect my problem very well.
I have an object DerivedType
in my code that is added to BaseType
:
BaseType someObject = Factory.GetItem(); //Actual type is DerivedType
I also have PropertyType
through reflection:
PropertyInfo someProperty = entity.GetType().GetProperties().First()
I would like to check if someObject
a value can be assigned PropertyType
to someProperty
. How can i do this?
source to share
If 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 second form, it is not entirely clear.
The easiest answer is to check:
(factory.GetDerivedObject() as SomeDerivedType) != null
After editing:
What you want to know is not that someObject is assigned to SomeProperty, but if it is hidden.
The base will be:
bool ok = someProperty.PropertyType.IsInstanceOfType(someObject);
But this only handles inheritance.
source to share
Since I see that yours is GetDerivedObject()
not generic and that you have to explicitly point its result to SomeDerivedType
, I assume that it GetDerivedObject
is defined as returning the underlying type for SomeDerivedType
(as a last resort, object
).
If so, this line:
typeof(SomeDerivedType).IsAssignableFrom(factory.GetDerivedObject().GetType());
translates into
typeof(SomeDerivedType).IsAssignableFrom(SomeBaseType);
which is usually false since you cannot assign a base type to a derived type (you need to explicitly state what you did).
source to share