715

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

0

11 Answers 11

1101

Try this:

this.GetType().Name
Sign up to request clarification or add additional context in comments.

21 Comments

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.
@EricLippert: If you type the name in, the compiler won't catch it if the class is renamed.
@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.
@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: ... and in C# 6 you can use the new nameof operator.
|
315

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

typeof(MyProgram).Name

11 Comments

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
@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()".
If you want to get inherited class name and this call is in the parent then it won't work.
This has the disadvantage of having to reference the type explicitly, which makes it less easily reusable.
In C# 6.0 or later you can do nameof(MyProgram).
|
294

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

nameof(MyProgram)

1 Comment

Great stuff; also works with type members (such as methods and properties) and even variables - see the docs.
150

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 Comments

Nice catch, although I think my method is preferred in this case.
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.
This doesn't seem to work anymore in the DNX (Dot Net Execution) framework. They removed the GetCurrentMethod() method and left only GetMethodFromHandle().
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.
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();
    }
}

Comments

17

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

this.GetType().BaseType.Name

Comments

12

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 Comments

DeclaringType is declared [Nullable(2)] so you get an warning when null check are active.
@Martin, please explain your comment. I don't get it?
12

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

var className = GetType().Name

Comments

4

This can be used for a generic class

typeof(T).Name

Comments

2

Get Current class name of Asp.net

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

1 Comment

DeclaringType is declared [Nullable(2)] so you get an warning when null check are active.
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 the documentation for CallerMemberNameAttribute

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.