this is my first question here so I hope I can articulate it well and hopefully it won't be too mind-numbingly easy.
I have the following class SubSim which extends Sim, which is extending MainSim. In a completely separate class (and library as well) I need to check if an object being passed through is a type of MainSim. So the following is done to check;
Type t = GetType(sim); //in this case, sim = SubSim if (t != null) { return t.BaseType == typeof(MainSim); }
Obviously t.BaseType is going to return Sim since Type.BaseType gets the type from which the current Type directly inherits.
Short of having to do t.BaseType.BaseType to get MainSub, is there any other way to get the proper type using .NET libraries? Or are there overrides that can be redefined to return the main class?
Thank you in advance
The base type is the type from which the current type directly inherits. Object is the only type that does not have a base type, therefore null is returned as the base type of Object.
A base class, in the context of C#, is a class that is used to create, or derive, other classes. Classes derived from a base class are called child classes, subclasses or derived classes. A base class does not inherit from any other class and is considered parent of a derived class.
The typeof is an operator keyword which is used to get a type at the compile-time. Or in other words, this operator is used to get the System. Type object for a type.
Use the is
keyword:
return t is MainSim;
There are 4 related standard ways:
sim is MainSim;
(sim as MainSim) != null;
sim.GetType().IsSubclassOf(typeof(MainSim));
typeof(MainSim).IsAssignableFrom(sim.GetType());
You can also create a recursive method:
bool IsMainSimType(Type t)
{ if (t == typeof(MainSim)) return true;
if (t == typeof(object) ) return false;
return IsMainSimType(t.BaseType);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With