Define a method in a base class that returns the name of itself (using reflection) - subclasses inherit this behavior

In C #, using reflection, is it possible to define a method in a base class that returns its own name (as a string) and whether subclasses inherit this behavior in a polymorphic way?

For instance:

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"  
+5
source share
1 answer
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 will get type meta information.

You can also do this,

public class Base
{

}

public class Subclass : Base
{

}

//In your client-code
Subclass subclass = new Subclass();
string className = subclass.GetType().Name;

EDIT

, getClassName() , [ .net framework], getClassName() , .

public class Base
{
    public string ClassName
    {
        get
        {
            return this.GetType().Name;
        }
    }
}

EDIT2

.

public class Base
{
    private string className;
    public string ClassName
    {
        get
        {
            if(string.IsNullOrEmpty(className))
                className = this.GetType().Name;
            return className;
        }
    }
}
+6

All Articles