Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BaseType of a Basetype

Tags:

c#

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

like image 323
Emmanuel F Avatar asked Oct 21 '08 14:10

Emmanuel F


People also ask

What is a base type?

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.

What is base type class in C#?

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.

Is Typeof C#?

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.


2 Answers

Use the is keyword:

return t is MainSim;
like image 110
matt b Avatar answered Oct 20 '22 01:10

matt b


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);
 }
like image 42
Mark Cidade Avatar answered Oct 20 '22 00:10

Mark Cidade