In C#, using reflection, is it possible to define method in the base class that returns its own name (in the form of a string) and have subclasses inherit this behavior in a polymorphic way?
For example:
public class Base
{
public string getClassName()
{
//using reflection, but I don't want to have to type the word "Base" here.
//in other words, DO NOT WANT get { return typeof(Base).FullName; }
return className; //which is the string "Base"
}
}
public class Subclass : Base
{
//inherits getClassName(), do not want to override
}
Subclass subclass = new Subclass();
string className = subclass.getClassName(); //className should be assigned "Subclass"
protected (C# Reference)The protected keyword is also part of the protected internal and private protected access modifiers. A protected member is accessible within its class and by derived class instances.
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.
The base class is specified by adding a colon, “:”, after the derived class identifier and then specifying the base class name. Note: C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from.
public class Base
{
public string getClassName()
{
return this.GetType().Name;
}
}
actually, you don't need to create a method getClassName() just to get the type-name
. You can call GetType() on any .Net object and you'll get the meta information of the Type.
You can also do it like this,
public class Base
{
}
public class Subclass : Base
{
}
//In your client-code
Subclass subclass = new Subclass();
string className = subclass.GetType().Name;
Moreover, should you really need to define getClassName() in any case, I'd strongly suggest to make it a property [as per .net framework design guide-lines] since the behavior of getClassName() is not dynamic and it will always return the same value every-time you call it.
public class Base
{
public string ClassName
{
get
{
return this.GetType().Name;
}
}
}
Optimized version After reading comment from Chris.
public class Base
{
private string className;
public string ClassName
{
get
{
if(string.IsNullOrEmpty(className))
className = this.GetType().Name;
return className;
}
}
}
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