tags:

views:

47

answers:

1

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"  
+5  A: 
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;

EDIT

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;
        }
    }
}

EDIT2

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;
        }
    }
}
this. __curious_geek
`this`, yuck!!!!
leppie
what's wrong with `this` ?
this. __curious_geek
I like this. :-)this.__curious_geek's answer is correct, but the default implementation of the .ToString() method returns the class name. You can't count on it because someone may override .ToString(), so this answer is better.
Chris McKenzie
Also, the property implementation above will not prevent the class name from being reevaluated. To do that, make a backing variable for the property and initialize it to this.GetType().Name;
Chris McKenzie
@Chris: At first I thought of including .ToString() in answer but I didn't include since it might get over-loaded.
this. __curious_geek
@Chris, @this. __curious_geek: latest version looks very optimal.
Khnle