Get the class name in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class MyClass { } public class Example { public static void Main() { MyClass myClass = new MyClass(); Console.WriteLine("The class type is {0}", myClass.GetType()); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; public class MyBaseClass { } public class MyDerivedClass: MyBaseClass { } public class Example { public static void Main() { MyBaseClass myBase = new MyBaseClass(); MyDerivedClass myDerived = new MyDerivedClass(); object o = myDerived; MyBaseClass b = myDerived; Console.WriteLine("mybase: Type is {0}", myBase.GetType()); Console.WriteLine("myDerived: Type is {0}", myDerived.GetType()); Console.WriteLine("object o = myDerived: Type is {0}", o.GetType()); Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType()); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; public class MyClass { public void printClassName() { Console.WriteLine("The class type is {0}", this.GetType().Name); } } public class Example { public static void Main() { MyClass myClass = new MyClass(); myClass.printClassName(); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
using System; using System.Reflection; public class Example { public static void Main() { string? className = MethodBase.GetCurrentMethod()?.DeclaringType?.Name; Console.WriteLine("The class type is {0}", className); } } |
Output:
The class type is Example
That’s all about getting the class name in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)