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?

+3


source to share


4 answers


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.

+5


source


Try to use

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

      



or

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

      

+1


source


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).

+1


source


Try it. It might work. Some minor changes may be required to compile.

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

typeof(SomeDerivedType).IsAssignableFrom(b1))

      

0


source







All Articles