EN
C# / .NET - get class name
3 points
In this short article, we would like to show how to get some class name in C#.
Quick solution:
xxxxxxxxxx
1
Type classType = someObject.GetType();
2
3
string className = classType.Name;
or:
xxxxxxxxxx
1
Type classType = typeof(SomeClass);
2
3
string className = classType.Name;
In this example, we use GetType()
function to get class type and Name
property to get class name.
xxxxxxxxxx
1
using System;
2
3
class Student
4
{
5
public string Name { get; private set; }
6
7
public Student(string name)
8
{
9
this.Name = name;
10
}
11
}
12
13
public class Program
14
{
15
public static void Main()
16
{
17
Student student = new Student("Tom");
18
Type type = student.GetType();
19
20
Console.WriteLine(type.Name);
21
}
22
}
Output:
xxxxxxxxxx
1
Student
In this example, we use typeof()
operator to get class type and Name
property to get class name. Using this approach we don't need to have class type instance.
xxxxxxxxxx
1
using System;
2
3
class Student
4
{
5
public string Name { get; private set; }
6
7
public Student(string name)
8
{
9
this.Name = name;
10
}
11
}
12
13
public class Program
14
{
15
public static void Main()
16
{
17
Type type = typeof(Student);
18
19
Console.WriteLine(type.Name);
20
}
21
}
Output:
xxxxxxxxxx
1
Student