C# Basics - Reflection
2023-01-31 21:59:17  C#  >> Basics

Reflection in C#

As Big Hard, Reflection provides objects (of type Type) that describe assemblies, modules, and types.

Generally speaking, we can use Reflection to get the information from an object of a Type type (mostly an instance of a class) and its fields and methods.

In C#, we use GetType() to get the exact runtime type of the current instance to realize Reflection.

1
public Type GetType();

Inheritance: Object -> MemberInfo -> Type
GetType() belongs to System.Object, which is the base class for all types in the .NET, so that it can return all .NET types.

.NET recognizes the following five categories of types:

Type Description
Class Derived from System.Object
Value types Derived from System.ValueType
Interfaces Derived from System.Object after .NET Framework 2.0
Enumerations Derived from System.Enum
Delegates Derived from System.MulticastDelegate

Common Used Methods

GetType()

Create a WPF project with a button for test.
Alt text

Add Button_Click function for the button and create a class Person.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
}
}
public class Person
{
public string Name_Per = "Person";
}

Then, create the instance for Person class.

Use Type function to get the type of instance, thereby getting the name of class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Person per = new Person();
Type tPer = per.GetType();
string v1 = tPer.Name;
MessageBox.Show(v1);
}
}
public class Person
{
public string Name_Per = "Person";
}

And display their name in message box.
Alt text

Any time we want to get information about an instance, for example, fields and methods of a class, we can use Reflection, which is its most basic role.


Now let’s see how reflection can be used between classes that have inheritance.

Create a class Student, which is inheritance from Person.

As above, create the instances for both classes and get their names by GetType().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Person per = new Person();
Student stu = new Student();

Type tPer = per.GetType();
Type tStu = stu.GetType();

string v1 = tPer.Name;
string v2 = tStu.Name;

MessageBox.Show(v1 + " " + v2);
}
}
public class Person
{
public string Name_Per = "Person";
}
public class Student: Person
{
public string Name_Stu = "Student";
}

Display both of their names.
Alt text

As you can see, the reflection only retrack the name of instance of current class. What if we want to get the fields in the class?

GetFields()

GetFields() will return all of the public fields that the instance can access.

It returns an array of FieldInfo.

1
public System.Reflection.FieldInfo[] GetFields ();

Modify the Button_Click function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private void Button_Click(object sender, RoutedEventArgs e)
{
Person per = new Person();
Student stu = new Student();

Type tPer = per.GetType();
Type tStu = stu.GetType();

var v1 = tPer.GetFields();
var v2 = tStu.GetFields();

string sPer = String.Empty;
string sStu = String.Empty;

// get Person's fields' names
foreach (var v in v1)
{
sPer += v.Name + " ";
}
// get Student's fields' names
foreach (var v in v2)
{
sStu += v.Name + " ";
}

MessageBox.Show(
"Person: " + sPer + "\n" + "Student: " + sStu);
}

In Person, it returns the only field, Name_Per.

In Student, it returns the fields, Name_Per and Name_Stu, from both classes, as Student inherits from Person. And it returns the fields in the order from child to its parent.

Alt text

typeof()

typeof() is similar to GetType(), both of them can return a Type type to extract the information.

Let’s use it in our previous example.

Modify the Button_Click function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private void Button_Click(object sender, RoutedEventArgs e)
{
Person per = new Person();
Student stu = new Student();

//Modify the GetType to typeof
Type tPer = typeof(Person);
Type tStu = stu.GetType();

var v1 = tPer.GetFields();
var v2 = tStu.GetFields();

string sPer = String.Empty;
string sStu = String.Empty;

// get Person's fields' names
foreach (var v in v1)
{
sPer += v.Name + " ";
}
// get Student's fields' names
foreach (var v in v2)
{
sStu += v.Name + " ";
}

MessageBox.Show(
"Person: " + sPer + "\n" + "Student: " + sStu);
}

typeof

As the result, they are returning totally same result.

Difference between typeof() and GetType()

typeof keyword takes the Type itself as an argument and returns the underline Type of the argument whereas GetType() can only be invoked on the instance of the type.

typeof()

1
Type t1= typeof(Student); // Student is a Type

GetType()

1
2
Student stu= new Student();
Type t2= stu.GetType(); // stu is an instance of the type Student.

In summary,

  1. The parameters of typeof can only be int, string, String, or custom types, like a class, and CANNOT be instances.

  2. GetType() and typeof both return a reference of System.Type.

  3. typeOf(): Get a Type of a Class

  4. GetType(): Get the Type of an instance of a Class


Good Day
😎