Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check dynamic object type by string comparison

Tags:

c#

dynamic

c#-4.0

What is the best way to check a base object if of certain type, myObject can have hierarchies at "n" level, I want to compare with string because myObject is dynamic and i do not have assembly access to vehicle

a) Car : Vehicle
b) BiCycle : TwoWheeler : Vehicle
c) Truck : Trailer : FourWheeler : Vehicle

dynamic myObject = someObject;
if(myObject is Vehicle)  // Works
if(myObject is "Vehicle") //How to ?
like image 993
Brazil Nut Avatar asked Mar 10 '26 05:03

Brazil Nut


1 Answers

you could use IsAssginableFrom

System.Type.GetType(typeNameAsString).IsAssignableFrom(myObject.GetType())

that test whether myObject can be assign to a storage location of the type identified by the name (a string) held in typeNameAsString.

This will only work for types that are actually loaded and you should use the fully qualified name.

like image 147
Rune FS Avatar answered Mar 12 '26 20:03

Rune FS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!