views:

387

answers:

4

Hi

Consider the following code:

public class MyClass
{
     public static string MyStaticMethod()
     {
          //string className = GetClassNameHere...
     }
}

Is it possible to get the name of the class in which the static method resides ? Due to the fact that im using a static method, it is not possible to use the this pointer to retrieve the type of the object that im currently working in.

+13  A: 

Try the following

return typeof(MyClass).Name;

Or also

return MethodBase.GetCurrentMethod().DeclaringType.Name;
JaredPar
Beat me to it! :)
Chalkey
+2  A: 

You can do this...

String className = typeof(MyClass).Name;
Chalkey
A: 

Try this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MethodBase m = MethodInfo.GetCurrentMethod();
            MemberInfo info = (MemberInfo)m;
            Console.WriteLine(info.DeclaringType.FullName);
            Console.ReadKey();
        }
    }
}

The console will show "ConsoleApplication1.Program" =)

Rob
OP is looking for the class name, not the method name.
JaredPar
Also, you shouldn't need to cast to MemberInfo. m.Name should be enough.
John Saunders
@JaredPar - Yup, I realised my bad, d'oh =)
Rob
A: 

I may be missing the point entirely here, but what's wrong with the string "MyClass"?

public class MyClass
{
     public static string MyStaticMethod()
     {
          string className = "MyClass";
          Console.WriteLine(className);
     }
}

You may argue that if MyClass is inherited, you would want the name of the inherited class instead. Then consider the following:

public class MyClass
{
    public static string MyStaticMethod()
    {
        string className = typeof(MyClass).Name;
        Console.WriteLine(className);
    }
}
public class MyOtherClass : MyClass{ }

Now, what do you think you will see in the Console if you invoke MyOtherClass.SomeMethod? The answer is "MyClass". So, looking up the class name dynamically will give you the exact same result as simply typing it in a string. The only upside I can see with getting it through Reflection is that it will still render the correct result if you rename the class.

Fredrik Mörk
He might want it to be refactoring-safe. And for inheritance of course, though that's tricky.
Wouter Lievens
It may be a rather good performance penalty for keeping it safe for refactoring. And as I point out in my answer, there is no inheritance upside since it is a static method; it will always return the name of the base class.
Fredrik Mörk