Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Checking if an object can cast to another object fails?

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?

like image 854
Ropstah Avatar asked Apr 06 '12 09:04

Ropstah


2 Answers

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.

like image 146
Henk Holterman Avatar answered Oct 12 '22 21:10

Henk Holterman


Try use

if (factory.GetDerivedObject() is SomeDerivedType)
{
//do
}

or

var tmp = factory.GetDerivedObject() as SomeDerivedType;
if (tmp != null)
{
//do
}
like image 20
ShurikEv Avatar answered Oct 12 '22 19:10

ShurikEv