1

Possible Duplicate:
Get type name without full namespace in C#

Does anybody know how we can get the name of a class in a simple way like what Java can do via class.getName() ?

NB: Yes, there are some messy workaround like CreateInstance of the class type and then get the name of object but I want a simple way.

Edit 1:

Actually, I need the class name in a method say X. Meanwhile, I don't want to loose type-safety and I'm not gonna allow other developers to pass a string to the method. Something like this:

void X( ??? class) // --> don't know how
{
     var className = get the name of class // --> which I don't know how
     Console.WriteLine(className);
}

X(tblEmployee); //--> usage of X, where tblEmployee is a POCO class
Community
  • 1
  • 1
Alireza
  • 10,237
  • 6
  • 43
  • 59

3 Answers3

10

You mean, like this?

typeof(YourClass).Name

To clarify, in .NET framework there's a class named Type. This class has a property named Name that retrieves the name of the class.

So, to retrieve the Type of a class in compile time you can use typeof.

var typeName = typeof(YourClass).Name

If you doesn't know the type at runtime, you can retrieve it with the GetType() method. This is common for all .NET objects.

Animal a = new Dog();
var typeName = a.GetType().Name;

Answer for Edit 1

You need to pass a Type parameter

void X(Type classType) 
{
     var className = classType.Name;
     Console.WriteLine(className);
}

And a call to X should be like this

X(typeof(YourClass));

or

X(YourInstance.GetType());
Agustin Meriles
  • 4,866
  • 3
  • 29
  • 44
1

If class is

  • instance of some type:

    class.GetType().Name;
    class.GetType().FullName; // with namespace
    
  • type itself:

    typeof(class).Name;
    typeof(class).Name; // with namespace
    
sll
  • 61,540
  • 22
  • 104
  • 156
1

Try this:

typeof(YourClass).FullName;
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68