This post will discuss how to get the class name in C#.

1. Using Object.GetType() method

You can use the Object.GetType() method to get the exact runtime type of the current instance. The following code example demonstrates the working of the GetType method for a simple class.

Download  Run Code

Output:

The class type is MyClass

 
Here’s the code example taken from MSDN, which gets the runtime type of the base and derived class instances:

Download  Run Code

Output:

mybase: Type is MyBaseClass
myDerived: Type is MyDerivedClass
object o = myDerived: Type is MyDerivedClass
MyBaseClass b = myDerived: Type is MyDerivedClass

2. Using Reflection

If you need the name of the enclosing class within a non-static method, you can invoke the GetType() method using this keyword:

Download  Run Code

Output:

The class type is MyClass

 
However, the GetType() method won’t work on static methods. You can use the MemberInfo.DeclaringType property instead, which can get the class that declares this member. Note that you need to include System.Reflection namespace for this to work.

Download  Run Code

Output:

The class type is Example

That’s all about getting the class name in C#.