In our programming journey, there are times when we might find ourselves in a situation where we need to obtain the class name as a string. This proves beneficial for many reasons, such as logging, debugging, or other programming endeavors.
In C#, there are different techniques available to do this, including the GetType()
method, the typeof
operator, the nameof
operator and the MethodBase.GetCurrentMethod()
method.
So, let’s dive in and explore these different approaches.
Use the GetType Method to Get a Class Name as a String
A part of the System.Object
class, the GetType()
method is invoked on an instance of an object. It returns a System.Type
object that has several accessible properties, including the Name
property, which contains the class name. Let’s look at an example of how we can utilize GetType()
from both inside and outside a class.
To start things off, let’s define the Car
class:
public class Car { public void DisplayClassName() { var className = GetType().Name; Console.WriteLine($"Class name: {className}"); } }
Here we can see that the Car
class has a method called DisplayClassName()
, where we retrieve the class name as a string by invoking GetType().Name
.
We can now instantiate the Car
class and call the DisplayClassName()
method on it :
public class Program { public static void Main() { var myCar = new Car(); myCar.DisplayClassName(); } }
This should return the class name as a part of the output to the console:
Class name: Car
We can also directly call GetType().Name
on the myCar
object to retrieve the class name from an external context. Let’s modify our Program
class to demonstrate this:
public class Program { public static void Main() { ... var className = myCar.GetType().Name; Console.WriteLine("Using GetType outside the class : " + className); } }
Here we can see that inside the Main()
method, we are now using myCar.GetType().Name
to get the name of the class as a string into the className
variable. In the next line, we use the same variable to print the class name to the console using string concatenation.
Do note that GetType()
method operates on an instance of an object; therefore, its application is not valid for static classes.
Use the typeof Operator
The typeof
operator fetches a System.Type
instance, representing a type at compile time. We can then tap into the Name
property of this Type
instance to get the class name both from inside and outside the class.
Let’s take the example of the Car
class again:
public class Car { public void DisplayClassNameUsingTypeOf() { var className = typeof(Car).Name; Console.WriteLine($"Class name: {className}"); } }
Here, we have the DisplayClassNameUsingTypeOf()
method where we use typeof(Car).Name
to get the class name at compile time. Then, we print it to the console using string interpolation.
Now when we call the DisplayClassNameUsingTypeOf()
on an instance of Car
class:
public class Program { public static void Main() { var myCar = new Car(); myCar.DisplayClassNameUsingTypeOf(); } }
This should produce the class name Car
as a part of the output to the console:
Class name: Car
Like the GetType()
method, we can use the typeof
operator from outside the context of the class. However, unlike the GetType()
method-based approach, we don’t need to create an instance of the Car
class anymore.
Let’s modify the Program
class to demonstrate this :
public class Program { public static void Main() { var classNameOutside = typeof(Car).Name; Console.WriteLine($"Class name: {classNameOutside}"); } }
In the Main()
method, we retrieve the class name from outside the class context by just using typeof(Car).Name
. Thus keeping the output unchanged.
Unlike the GetType()
method, we can use this typeof
operator from within a static class to retrieve its name.
Let’s demonstrate this with the help of a static CarInfo
class:
public static class CarInfo { public static string DisplayClassNameWithTypeOf() { return typeof(CarInfo).Name; } }
Here, we define a static DisplayClassNameWithTypeOf()
method within the CarInfo
class, that returns the output of typeof(Car).Name
.
Let’s modify our Program
class as well:
public class Program { public static void Main() { var className = CarInfo.DisplayClassNameWithTypeOf(); Console.WriteLine("Using typeof: " + className); } }
As a result, the output that we see on the console is:
Using typeof: CarInfo
The argument to the typeof
operator must be the name of a type or a type parameter. To explore the typeof
operator in-depth, please refer to this link.
Use the nameof Operator to Get a Class Name as a String
The nameof
operator gives us the name of a type or a member as a string at compile time. To see how it works let’s use the Car
class with the DisplayClassName()
method as an example:
public class Car { public void DisplayClassNameUsingNameOf() { var className = nameof(Car); Console.WriteLine($"Class name: {className}"); } }
Inside the DisplayClassNameUsingNameOf()
method we use nameof(Car)
to capture the name of the class and then print it to the console.
Next, we will modify the Program
class:
public class Program { public static void Main() { var myCar = new Car(); myCar.DisplayClassNameUsingNameOf(); var classNameOutside = nameof(Car); Console.WriteLine($"Class name from outside the class: {classNameOutside}"); } }
In this code snippet, we instantiate the Car
class again and then call the DisplayClassNameUsingNameOf()
method on the instance. Additionally, like the typeof
operator, we call the nameof
expression directly on the Car
class to get its name as a string and output it to the console:
Class name: Car Class name from outside the class: Car
Like the typeof
operator, the nameof
operator can also be used inside a static class.
Let’s use the example of CarInfo
static class again:
public static class CarInfo { public static string DisplayClassNameWithNameOf() { return nameof(CarInfo); } }
Next, we will modify the Program
class:
public class Program { public static void Main() { var className = CarInfo.DisplayClassNameWithNameOf(); Console.WriteLine("Using typeof: " + className); } }
It is important to mention that, same as the typeof
operator, the nameof
expression accepts the type as an argument. This article dives deeper into how the nameof
expression works.
Use Reflection
Lastly, we’re going to look into the MethodBase.GetCurrentMethod()
method, which is a part of the System.Reflection
namespace. This method fetches a MethodBase
object representing the currently executing method, and we can derive the class name from it:
using System.Reflection; public class Car { public void DisplayClassNameUsingReflection() { var className = MethodBase.GetCurrentMethod().DeclaringType.Name; Console.WriteLine($"Class name: {className}"); } }
Inside the DisplayClassNameUsingReflection()
instance method we now use MethodBase.GetCurrentMethod().DeclaringType.Name
to capture the name of the class.
Let’s modify the Program
class:
public class Program { public static void Main() { var myCar = new Car(); myCar.DisplayClassNameUsingReflection(); } }
Here, we first create an instance of the Car
class and then we call the DisplayClassNameUsingReflection()
on the instance to get the desired output.
This approach stands out from using the typeof
operator and the nameof
expression as it doesn’t require an explicit reference to the class within the DisplayClassName()
method. Instead, MethodBase.GetCurrentMethod().DeclaringType.Name
fetches the class name from within the class context without needing to call the class explicitly.
Still, it’s worth noting a couple of limitations. First, this approach can only fetch the class name from within an instance of the class, not from an external context, which is something we can do with the GetType()
method or typeof
operator. Second, similar to the GetType()
method, this method isn’t suitable for static classes because it needs an instance of the class to operate, which static classes do not provide.
Conclusion
Each method offers unique advantages and the selection of a suitable method will largely be dictated by specific requirements and the context of the application. Options range from the versatility of GetType()
, the compile-time security of typeof
, the brevity of nameof
, to the reflection capabilities of MethodBase.GetCurrentMethod()
. Hence, a wide range of resources are available to meet various programming needs in this regard.