tags:

views:

235

answers:

5

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

+14  A: 

Try this:

this.GetType().Name
micahtan
Won't work in a static method ;)
Thomas Levesque
@Thomas - True, although the OP will have to use reflection to do so. This may or may not matter.
micahtan
@micahtan: you could also create a static method that creates an instance and returns the Name property. Definitely easier than using Reflection.
MusiGenesis
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
+4  A: 

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

typeof(MyProgram).Name
ChaosPandion
+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
Nice catch, although I think my method is preferred in this case.
ChaosPandion
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
A: 

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

this.GetType().BaseType.Name
mikeschuld
A: 

There is a difference between GetType and typeof. GetType will return different name when inheritance is in place

tomasvoracek