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

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

Example:

public abstract class A { private Type GetInfo() { return System.Attribute.GetCustomAttributes(this.GetType()); } } public class B : A { //Fields here have some custom attributes added to them } 

Or do I just need to make an abstract method that derived classes will have to implement as follows?

 public abstract class A { protected abstract Type GetSubType(); private Type GetInfo() { return System.Attribute.GetCustomAttributes(GetSubType()); } } public class B : A { //Fields here have some custom attributes added to them protected Type GetSubType() { return GetType(); } } 
+86
inheritance polymorphism c #
Apr 25 2018-11-11T00:
source share
3 answers

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

There is no reason for your GetSubType() method.

+94
Apr 25 '11 at 16:40
source share

GetType always returns the type that was actually created. those. most derived type. This means that your GetSubType behaves exactly like GetType and therefore is not needed.

To statically obtain type information of some type, you can use typeof(MyClass) .

There is an error in your code: System.Attribute.GetCustomAttributes returns Attribute[] not Type .

+16
Apr 25 2018-11-21T00:
source share

GetType always returns the actual type.

The reason for this is deep in .NET and the CLR , because JIT and CLR use the .GetType method to create an object of type in memory that contains information about the object, and all access to the object and compilation is done through this instance of the type.

For more information, check out Microsoft Press CLR through C #.

+7
Aug 07 '13 at 18:09 on
source share



All Articles