Home > Backend Development > C#.Net Tutorial > Reflection in C#

Reflection in C#

PHPz
Release: 2024-09-03 15:19:12
Original
937 people have browsed it

Reflection in C# is the process of collecting information on its features and operating on itself. The collecting information includes the properties, type, events, and methods of an object; reflection is useful in finding all types of assemblies. Dynamically it invokes an assembly method we can dynamically bind or get the type to or from an existing object; reflection is used to create an instance of the type. We can access its properties and fields the main purpose of reflection used to read its metadata for searching the assemblies during runtime.

Why do we need Reflection in C#?

We need the reflection in C# to obtain the type information during runtime; it is the process of observing managed code to read its metadata for finding modules and assemblies during runtime. Reflection reflects in the program by extracting metadata from its assemblies, which is used to modify its behavior.  The System. Reflection namespace allows you to access the managed view of methods, loaded types, and fields to create dynamically and invoke types. We require the reflection for the following application process to be done there are,

  • During the runtime process, reflection allows a view of attribute information.
  • Reflection allows late binding to properties and methods
  • It examines several types of assemblies and their types
  • It allows the creation of new types during runtime and performs various tasks by following those types.

How Does Reflection work in C#?

C# Reflection enables the application to get information itself, and also it operates on itself. It effectively searches all types of assemblies and invokes assembly methods dynamically.

The major important class which is used in reflection is System. Type class is an abstract class representing a type called CTS (Common Type System). Using this class, we can find the types we used in namespace modules and verify that the given type is a value or reference type. By using the following items, we can parse the metadata tables,

  • Methods
  • Properties
  • Events
  • Fields

Using the reflection, Late Binding is achieved; during compile time, we might not know which assembly to load for these reasons; we load the appropriate assembly by asking the users to enter the assembly name and type at run time execution. By approaching direct loading on assemblies, we go with System. Reflection. Assembly by getting three static types are,

  • LoadFrom
  • LoadModule
  • LoadWithPartialName

Considering that the assembly is an exe or dll file makes that file as portable executable files for Common Type System, which have an extension of .dll or .exe. A portable Executable file is a metadata that contains several tables as follows,

  • Method definition table
  • Type definition table
  • Field definition table

Examples of Reflection in C#

Given below are the examples of Reflection in C#:

Example #1

using System;
using System.Reflection;
namespace Reflection_Sample {
class Program_1 {
// Main Method
static void Main(string[] args)
{
// to initialize _type as typeof string
Type _type = typeof(string);
// by using the Reflection to find and in any sort of data related to _type
Console.WriteLine("Name : {0}", _type.Name);
Console.WriteLine("Full Name : {0}", _type.FullName);
Console.WriteLine("Namespace : {0}", _type.Namespace);
Console.WriteLine("Base Type : {0}", _type.BaseType);
}
}
}
Copy after login

In the above code, we loaded the type _type as a string using the typeof method. Then we relate reflection on _type to come across the information on string class, including the namespace, name, fullname, and basetype.

Output:

Reflection in C#

Example #2

In this program, we get the assembly by defining the typeof method and get through by this way _type. Assembly. Let’s see the example program

using System;
using System.Reflection;
public class ReflectionExample
{
public static void Main()
{
Type _type = typeof(System.String);
Console.WriteLine(_type.Assembly);
}
}
Copy after login

Output:

Reflection in C#

Example #3

In this program, we show the metadata using the reflection; it includes methods, classes, and various parameterized constructors. Let’s see the below example,

using System;
using System.Reflection;
namespace Sample_ReflectionMetadata
{
// to define a class StudentDetails
class StudentDetails
{
// defining the Properties
public int _RollNo
{
get;
set;
}
public string _Name
{
get;
set;
}
// Constructor with no arguments
public StudentDetails()
{
_RollNo = 0;
_Name = string.Empty;
}
// this is a Parameterised Constructor with 2 parameters
public StudentDetails(int _Srollno, string _Sname)
{
_RollNo = _Srollno;
_Name = _Sname;
}
// to invoke method to Display Student Details
public void StudentDisplayData()
{
Console.WriteLine("Roll Number : {0}", _RollNo);
Console.WriteLine("Name : {0}", _Name);
}
}
class ReflectionClass
{
// Main Method
static void Main(string[] args)
{
// to declare Assembly and loading the current assembly
Assembly _executing = Assembly.GetExecutingAssembly();
Type[] _types = _executing.GetTypes();
foreach(var item in _types)
{
Console.WriteLine("Class : {0}", item.Name);
// storing the methods  in array
MethodInfo[] methods = item.GetMethods();
foreach(var method in methods)
{
// for displaying each method
Console.WriteLine("--> Method : {0}", method.Name);
// to store the parameters in array
ParameterInfo[] parameters = method.GetParameters();
foreach(var arg in parameters)
{
Console.WriteLine(" Parameter : {0} Type : {1}",
arg.Name, arg.ParameterType);
}
}
}
}
}
}
Copy after login

Output:

Reflection in C#

Example #4

Reflection is the process of observing and altering its real structure and behavior dynamically. In the below sample program, Reflection works that we can analyze and alter the information in the application during runtime.  Let’s see the example,

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ReflectionSample
{
class Program
{
private static int value_1= 15, value_2 = 25, value_3 = 30;
static void Main(string[] args)
{
Console.WriteLine("The Values are = " + (value_1 + value_2 + value_3));
Console.WriteLine("Input the Name of variable to be altered:");
string _varName = Console.ReadLine();
Type _type = typeof(Program);
FieldInfo _fieldInfo = _type.GetField(_varName, BindingFlags.NonPublic | BindingFlags.Static);
if(_fieldInfo != null)
{
Console.WriteLine("The Latest Value of " + _fieldInfo.Name + " is " + _fieldInfo.GetValue(null) + ". Input NeW Value:");
string newValue = Console.ReadLine();
int newInt;
if(int.TryParse(newValue, out newInt))
{
_fieldInfo.SetValue(null, newInt);
Console.WriteLine(" Final Values are = " + (value_1 + value_2 + value_3));
}
Console.ReadKey();
}
}
}
}
Copy after login

Here we can change the value of a variable during runtime by knowing its name. By using reflection, we can achieve these types of methods. Let’s see the below output as follows,

Output:

Reflection in C#

Conclusion

I hope you have enjoyed the article; C# Reflection covers the important functionalities in .Net here; we have learned how Reflection works in C#.Net with several examples. I hope this article will help you with a good understanding.

The above is the detailed content of Reflection in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template