686

If I have a class called MyProgram, is there a way of retrieving "MyProgram" as a string?

0

11 Answers 11

1069

Try this:

this.GetType().Name
21
  • 42
    If you're in a static method then the developer knows what the name of the type is. You can just type it in as a string in the source code. Commented Jan 22, 2010 at 0:33
  • 185
    @EricLippert: If you type the name in, the compiler won't catch it if the class is renamed.
    – Halvard
    Commented Mar 14, 2013 at 11:18
  • 13
    @Halvard: First, if the static method is in the current type then the name is optional; if you're worried about it changing, omit it. Second, Visual Studio will automatically give you a smart tag when you rename a class that renames all instances of it. And third, if you're renaming a class then odds are good you're going to have to make a lot of changes in a lot of places already. Commented Mar 14, 2013 at 14:41
  • 14
    @EricLippert You are right. Any new version of Visual Studio or ReSharper will catch the strings with the same name as the class being renamed. My previous comment is just some old, now useless knowledge ...
    – Halvard
    Commented Mar 15, 2013 at 9:24
  • 31
    @Halvard: ... and in C# 6 you can use the new nameof operator. Commented Feb 24, 2015 at 21:46
309

I wanted to throw this up for good measure. I think the way @micahtan posted is preferred.

typeof(MyProgram).Name
11
  • 39
    This is actually better, because: 1. It will work in static context 2. It is compile time computed, so it doesn't cost like reflection
    – Gilbert
    Commented Dec 14, 2013 at 15:38
  • 9
    @JimBalter It has multiple advantages: 1. Static context. 2. The type portion will not be re-evaluated by the CLR each time - it will be written to the MSIL. 3. It protects you from someone declaring a new "GetType()".
    – Gilbert
    Commented Apr 16, 2014 at 19:48
  • 14
    If you want to get inherited class name and this call is in the parent then it won't work.
    – Gh61
    Commented Jul 25, 2014 at 9:33
  • 21
    This has the disadvantage of having to reference the type explicitly, which makes it less easily reusable.
    – cprcrack
    Commented Feb 16, 2015 at 17:31
  • 35
    In C# 6.0 or later you can do nameof(MyProgram). Commented Nov 7, 2017 at 13:34
287

With C# 6.0, you can use the nameof operator:

nameof(MyProgram)
1
  • 6
    Great stuff; also works with type members (such as methods and properties) and even variables - see the docs.
    – mklement0
    Commented Jun 8, 2016 at 22:23
148

Although micahtan's answer is good, it won't work in a static method. If you want to retrieve the name of the current type, this one should work everywhere:

string className = MethodBase.GetCurrentMethod().DeclaringType.Name;
4
  • 3
    Nice catch, although I think my method is preferred in this case. Commented Jan 21, 2010 at 21:36
  • 5
    This Won't work for non-virtual methods, as it will return the name of the type that the method is declared and implemented in, (possibly up the inheritance chain), not the concrete type of the instance you are actually executing the code from. Commented Jan 21, 2010 at 21:56
  • 2
    This doesn't seem to work anymore in the DNX (Dot Net Execution) framework. They removed the GetCurrentMethod() method and left only GetMethodFromHandle().
    – Astaar
    Commented Sep 15, 2015 at 10:12
  • This is exactly what I needed to get the name of the concrete class currently executing code called from a virtual function in a descendant.
    – DrFloyd5
    Commented Mar 25, 2020 at 17:35
21

If you need this in derived classes, you can put that code in the base class:

protected string GetThisClassName() { return this.GetType().Name; }

Then, you can reach the name in the derived class. Returns derived class name. Of course, when using the new keyword "nameof", there will be no need like this variety acts.

Besides you can define this:

public static class Extension
{
    public static string NameOf(this object o)
    {
        return o.GetType().Name;
    }
}

And then use like this:

public class MyProgram
{
    string thisClassName;

    public MyProgram()
    {
        this.thisClassName = this.NameOf();
    }
}
17

For reference, if you have a type that inherits from another you can also use

this.GetType().BaseType.Name
0
10

this can be omitted. All you need to get the current class name is:

GetType().Name
10

Use this

Let say Application Test.exe is running and function is foo() in form1 [basically it is class form1], then above code will generate below response.

string s1 = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;

This will return .

s1 = "TEST.form1"

for function name:

string s1 = System.Reflection.MethodBase.GetCurrentMethod().Name;

will return

s1 = foo 

Note if you want to use this in exception use :

catch (Exception ex)
{

    MessageBox.Show(ex.StackTrace );

}
2
  • DeclaringType is declared [Nullable(2)] so you get an warning when null check are active.
    – Martin
    Commented Oct 11, 2019 at 14:50
  • @Martin, please explain your comment. I don't get it?
    – NoChance
    Commented Feb 1, 2020 at 1:45
4

This can be used for a generic class

typeof(T).Name

3

Get Current class name of Asp.net

string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();
1
  • 1
    DeclaringType is declared [Nullable(2)] so you get an warning when null check are active.
    – Martin
    Commented Oct 11, 2019 at 14:51
2

The easiest way is to use the call name attribute. However, currently, there is no attribute class that returns the class name or the namespace of the calling method.

See: CallerMemberNameAttributeClass

public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    System.Diagnostics.Trace.WriteLine("message: " + message);
    System.Diagnostics.Trace.WriteLine("member name: " + memberName);
    System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
    System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber);
}

// Sample Output:
//  message: Something happened.
//  member name: DoProcessing
//  source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs
//  source line number: 31

Not the answer you're looking for? Browse other questions tagged or ask your own question.