6

Example:

namespace MyProgram.Testing
{

    public class Test1
    {
        public void TestMethod()
        {
            String actualType = this.GetType().FullName.ToString();
            return;
        }

        public static String GetInheritedClassName()
        {
            return System.Reflection.MethodBase.GetCurrentMethod().ReflectedType.FullName;
        }

    }

    public class Test2 : Test1
    {
    }

    public class Test3
    {
       String test2ClassName = Test2.GetInheritedClassName();
    }
}

Anyway, I want it to return "MyProgram.Testing.Test2" but instead Test2.GetInheritedClassName() returns "MyProgram.Testing.Test1". What do I have to put into that static class to get it to return that (if possible)?

copystart
  • 107
  • 1
  • 5
  • I don't think this is possible, the static members always live on the base class that defined them. But I'm sure someone else can provide a more technical answer. – CodingGorilla Jul 21 '11 at 14:42

2 Answers2

6

It's not possible. When you call Test2.GetInheritedClassName, it's actually Test1.GetInheritedClassName that is called, because Test2.GetInheritedClassName doesn't really exists (btw, some tools like Resharper would show a warning: Access to a static member of a type via a derived type)

Static members don't participate in inheritance, which is kind of logical since inheritance only makes sense when you're dealing with instances...

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
1

The code that's printing out the type is the base-class method. Except for rare Reflection scenarios such as you provide above, execution wouldn't be affected by whether the method is called using the derived type or the base type, so the system makes no distinction.

You could, however, get around this by defining a generic base type:

    class ClassNameTesterBase<T>where T:ClassNameTester<T>
    {
        public static String getName() { return (typeof(T)).Name; }
    }

and then defining the other types of interest:

    class ClassNameTester1<T&gt : ClassNameTesterBase<T> ...
    class ClassNameTester2<T&gt : ClassNameTester1<T> ...

One may then if desired define leaf classes:

    class ClassNameTester1 : ClassNameTester1<ClassNameTester1> { }
    class ClassNameTester2 : ClassNameTester2<ClassNameTester2> { }

One slight caveat here is that ClassNameTester2 derives its innards from from ClassNameTester1<T> but is not substitutable for anything having to do with the ClassNameTester1<ClassNameTester1>; if it's being used as a static class, though, that shouldn't be a problem.

supercat
  • 77,689
  • 9
  • 166
  • 211