If I have a class called MyProgram
, is there a way of retrieving "MyProgram" as a string?
11 Answers
Try this:
this.GetType().Name
-
42If 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.– HalvardCommented 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 ...– HalvardCommented 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
I wanted to throw this up for good measure. I think the way @micahtan posted is preferred.
typeof(MyProgram).Name
-
39This is actually better, because: 1. It will work in static context 2. It is compile time computed, so it doesn't cost like reflection– GilbertCommented 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()".– GilbertCommented Apr 16, 2014 at 19:48
-
14If you want to get inherited class name and this call is in the parent then it won't work.– Gh61Commented Jul 25, 2014 at 9:33
-
21This has the disadvantage of having to reference the type explicitly, which makes it less easily reusable.– cprcrackCommented Feb 16, 2015 at 17:31
-
35
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;
-
3Nice catch, although I think my method is preferred in this case. Commented Jan 21, 2010 at 21:36
-
5This 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
-
2This doesn't seem to work anymore in the DNX (Dot Net Execution) framework. They removed the GetCurrentMethod() method and left only GetMethodFromHandle().– AstaarCommented 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.– DrFloyd5Commented Mar 25, 2020 at 17:35
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();
}
}
For reference, if you have a type that inherits from another you can also use
this.GetType().BaseType.Name
this
can be omitted. All you need to get the current class name is:
GetType().Name
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 );
}
-
DeclaringType is declared
[Nullable(2)]
so you get an warning when null check are active.– MartinCommented Oct 11, 2019 at 14:50 -
Get Current class name of Asp.net
string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();
-
1DeclaringType is declared
[Nullable(2)]
so you get an warning when null check are active.– MartinCommented Oct 11, 2019 at 14:51
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