Reputation: 1132
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
Upvotes: 11
Views: 6880
Reputation: 100057
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);
}
Upvotes: 22
Reputation: 1132
The 'is' option didn't work for me. It gave me the warning; "The given expression is never of the provided ('MainSim') type", I do believe however, the warning had more to do with the framework we have in place. My solution ended up being:
return t.BaseType == typeof(MainSim) || t.BaseType.IsSubclassof(typeof(MainSim));
Not as clean as I'd hoped, or as straightforward as your answers seemed. Regardless, thank you everyone for your answers. The simplicity of them makes me realize I have much to learn.
Upvotes: 1
Reputation: 955
How about "is"?
http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx
Upvotes: 0
Reputation: 103605
if (sim is MainSim)
is all you need. "is" looks up the inheritance tree.
Upvotes: 10