i would like to get the type of the derived class from a static method of its base class.
How can this be accomplished?
Thanks!
class BaseClass { static void Ping () { Type t = this.GetType(); // should be DerivedClass, but it is not possible with a static method } } class DerivedClass : BaseClass {} // somewhere in the code DerivedClass.Ping();
Even without the base keyword, you can access the static methods of a base class as if they were in the class you are calling from. I only tested this when calling a base static method from a derived class's static method. Might not work if you are calling from an instance method to a static method.
If you're trying to get the base class name, it'd be something like: Type classType = typeof(YourClass); Type baseType = classType. BaseType; string baseClassName = baseType.Name; Note that, if you recursively search the base types, when you call BaseType on typeof(System.
Object Slicing in C++ In C++, a derived class object can be assigned to a base class object, but the other way is not possible.
No, you cannot access any derived class members using base class pointer even pointing to a derived class instance. However you can access those values though methods of derived class.
This can be accomplished easily using the curiously recurring template pattern
class BaseClass<T> where T : BaseClass<T> { static void SomeMethod() { var t = typeof(T); // gets type of derived class } } class DerivedClass : BaseClass<DerivedClass> {}
call the method:
DerivedClass.SomeMethod();
This solution adds a small amount of boilerplate overhead because you have to template the base class with the derived class.
It's also restrictive if your inheritance tree has more than two levels. In this case, you will have to choose whether to pass through the template argument or impose the current type on its children with respect to calls to your static method.
And by templates I, of course, mean generics.
If I'm not mistaken, the code emitted for BaseClass.Ping()
and DerivedClass.Ping()
is the same, so making the method static without giving it any arguments won't work. Try passing the type as an argument or through a generic type parameter (on which you can enforce an inheritance constraint).
class BaseClass { static void Ping<T>() where T : BaseClass { Type t = typeof(T); } }
You would call it like this:
BaseClass.Ping<DerivedClass>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With