tags:

views:

449

answers:

5

Hello, 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

+4  A: 
if (sim is MainSim)

is all you need. "is" looks up the inheritance tree.

James Curran
+6  A: 

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);
 }
Mark Cidade
I like that recursive method, and I think I'm going to try that instead of my solution. Thank you!
Agent Worm
+1  A: 

Use the is keyword:

return t is MainSim;
matt b
+1  A: 

How about "is"?

http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx

mspmsp
A: 

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.

Agent Worm
You probably did "return t is MainSim" instead of "return sim is MainSim".
Hallgrim
Initially I did try that, What I left out of my question is that the object 'sim' would be a CollectionRow object, not necessarily a Sim object per se, that is why there is the call Type t = GetType(sim). I tried a couple of other things but it was returning false otherwise.
Agent Worm