This is it
This is it

Reputation: 789

How to get the name of the class without instantiating object or having a static method?

I hate to see the name of the class used as a string parameter like "FileDownloader" in the code, and I would like to use something like this FileDownloader.Name(), where FileDownloader is name of the class.
Only problem is that I can't find out how to do that without instantiating object or creating a static method...

Is there a way to get a class name in .net without having the object instance and without creating a static method that returns the name of the class?

Upvotes: 6

Views: 2740

Answers (4)

Erik A. Brandstadmoen
Erik A. Brandstadmoen

Reputation: 10608

In VB.Net:

Dim sf As StackFrame = New StackFrame()
Dim mb As MethodBase = sf.GetMethod()
Dim className = mb.DeclaringType.Name

There you go. Totally dynamic. Just be careful about refactoring... If you move it to another class, the class name will change... :)

Upvotes: 0

Morten
Morten

Reputation: 3854

Try typeof(YourClass).name. This should expose the name of your class

Upvotes: 1

Nick
Nick

Reputation: 25828

use the typeof operator:

typeof ( FileDownloader).Name

Upvotes: 3

Anton Gogolev
Anton Gogolev

Reputation: 115867

Sure:

var name = typeof(FileDownloader).Name;

Upvotes: 16

Related Questions