If I have a class called MyProgram, is there a way of retrieving "MyProgram" as a string?
If I have a class called MyProgram, is there a way of retrieving "MyProgram" as a string?
I wanted to throw this up for good measure. I think the way @micahtan posted is preferred.
typeof(MyProgram).Name
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;
For reference, if you have a type that inherits from another you can also use
this.GetType().BaseType.Name
Get Current class name of Asp.net
string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();
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