Ropstah
Ropstah

Reputation: 17794

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?

Upvotes: 5

Views: 3510

Answers (4)

samar
samar

Reputation: 5201

Try this. It might work. It might require some minor changes for it to compile.

TypeBuilder b1 = moduleBuilder.DefineType(factory.GetDerivedObject().GetType().Name, TypeAttributes.Public, typeof(SomeDerivedType));

typeof(SomeDerivedType).IsAssignableFrom(b1))

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273179

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.

Upvotes: 7

Paolo Falabella
Paolo Falabella

Reputation: 25844

Since I see that your GetDerivedObject() is not generic and that you have to cast its result explicitly to SomeDerivedType, I'm assuming that GetDerivedObject is defined as returning a base type for SomeDerivedType (in the extreme case, an object).

If so, this line:

typeof(SomeDerivedType).IsAssignableFrom(factory.GetDerivedObject().GetType());

translates to

typeof(SomeDerivedType).IsAssignableFrom(SomeBaseType);

which is generally false, as you can't assign a base type to a derived type (you need to cast explicitly, which is what you did).

Upvotes: 1

ShurikEv
ShurikEv

Reputation: 170

Try use

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

or

var tmp = factory.GetDerivedObject() as SomeDerivedType;
if (tmp != null)
{
//do
}

Upvotes: 1

Related Questions