If I have a class called MyProgram is there a way of retrieving "MyProgram" as a string?
Won't work in a static method ;)
Thomas Levesque
2010-01-21 21:35:38
@Thomas - True, although the OP will have to use reflection to do so. This may or may not matter.
micahtan
2010-01-21 21:58:16
@micahtan: you could also create a static method that creates an instance and returns the Name property. Definitely easier than using Reflection.
MusiGenesis
2010-01-21 22:42:15
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.
Eric Lippert
2010-01-22 00:33:48
+4
A:
I wanted to throw this up for good measure. I think the way @micahtan posted is preferred.
typeof(MyProgram).Name
ChaosPandion
2010-01-21 21:32:59
+8
A:
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;
Thomas Levesque
2010-01-21 21:35:22
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.
Charles Bretana
2010-01-21 21:56:00
A:
For reference, if you have a type that inherits from another you can also use
this.GetType().BaseType.Name
mikeschuld
2010-01-21 21:36:03
A:
There is a difference between GetType and typeof. GetType will return different name when inheritance is in place
tomasvoracek
2010-01-21 21:36:35