Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will GetType() return the most derived type when called from the base class?

People also ask

What is derived and base class in C#?

The class whose members are inherited is called the base class. The class that inherits the members of the base class is called the derived class. C# and . NET support single inheritance only.

What is a derived class in C#?

A derived class, in the context of C#, is a class created, or derived from another existing class. The existing class from which the derived class gets created through inheritance is known as base or super class.

What is the inheritance in c sharp?

In C#, inheritance allows us to create a new class from an existing class. It is a key feature of Object-Oriented Programming (OOP). The derived class inherits the fields and methods of the base class. This helps with the code reusability in C#.


GetType() will return the actual, instantiated type. In your case, if you call GetType() on an instance of B, it will return typeof(B), even if the variable in question is declared as a reference to an A.

There is no reason for your GetSubType() method.


GetType always returns the type that was actually instantiated. i.e. the most derived type. This means your GetSubType behaves just like GetType itself and thus is unnecessary.

To statically get the type information of some type you can use typeof(MyClass).

Your code has a mistake though: System.Attribute.GetCustomAttributes returns Attribute[] not Type.


GetType always returns the actual type.

The reason for it is deep in the .NET framework and CLR, as the JIT and CLR use the .GetType method to create a Type object in memory that holds the information on the object, and all access to the object and compilation are via this Type instance.

For more information, take a look in the book "CLR via C#" from Microsoft Press.