C# Reflection

In C# programming, reflection refers to the dynamic analysis of type metadata during program execution. The necessary classes for this process are found within the System.Reflection namespace. This functionality enables the exploration of details related to classes, methods, properties, and fields. Through reflection, developers can dynamically instantiate objects, invoke methods, and retrieve data. This feature finds frequent application in tasks such as serialization, testing, and implementing plugin architectures.

The styling for the placeholder diagram includes a background with a linear gradient, border radius of 12 pixels, padding of 40 pixels, margin of 20 pixels on top and bottom, and centered text alignment. Inside the diagram, there is an icon with a font size of 3rem and a margin-bottom of 10 pixels. Additionally, the text within the diagram is colored with #9ca3af and has a font size of 1rem.

Namespace for Reflection

The System.Reflection namespace contains the necessary classes and interfaces essential for implementing reflection in C#.

Example

using System.Reflection;

In this particular format,

  • utilizing: This term is employed to add a namespace in a C# program.
  • Reflection: This namespace encompasses all the necessary classes and interfaces for reflection.
  • C# Reflection Example

Let's consider an example to demonstrate the concept of reflection in C#.

Example

Example

using System;	

class C# Tutorial

{	

    public string name;

    public int age;

    public void greet()

    {

        Console.WriteLine("Welcome! ");

    }

}

class tech

{

    static void Main()

    {

        // Get type 

        Type type = typeof(C# Tutorial);

        Console.WriteLine("Class Name is " + type.Name );

        Console.WriteLine("\nThe fields are ");

        foreach (var f in type.GetFields())

        {

            Console.WriteLine("- " + f.Name );

        }

        Console.WriteLine("\n The methods are " );

        foreach ( var m in type.GetMethods())

        {

            Console.WriteLine("- " + m.Name );

        }

    }

}

Output:

Output

Class Name is C# Tutorial

 The fields are 

- name

- age

 The methods are 

- greet

- Equals

- GetHashCode

- GetType

- ToString

Explanation:

In this instance, we are outlining a class called Individual which includes two accessible attributes, namely name and age, along with a function named salutation. The function specifically displays the message "Hello" to the Console window. Within the Main function of the C# Guide class, we employ the typeof(Individual) function to obtain the class type details of the Individual class. Subsequently, it reveals the class name by utilizing the GetFields and GetMethods techniques.

Application of Reflection:

Reflection has several applications in the C# programming language . Some of them are as follows:

  • It allows for access to attribute data during program execution.
  • It enables examining and instantiating various types or classes from an assembly.
  • It allows calling methods and accessing properties during run time. It also supports late binding.
  • It allows the creation and use of new types during program execution.
  • Accessing Metadata using Reflection

In C#, the concept of reflection enables the examination of attribute details. To retrieve the attributes linked to a class, the initial step involves instantiating a MemberInfo object from the System.Reflection namespace. This is achieved by creating an object of the desired class, as illustrated:

Example

System.Reflection.MemberInfo info = typeof(MyClass);

C# Reflection Hierarchy

In C#, the System.Reflection namespace offers the functionality for reflection, presenting a well-defined structure of metadata classes that embody assemblies, modules, types, and their constituents. Within this namespace, you can find classes like.

The <style> CSS class includes styling properties for a placeholder diagram. This class sets a background color using a linear gradient, adds border radius, padding, margin, and aligns text at the center. Within this class, there are specific styles for the placeholder icon and text. The icon has a font size of 3rem and a margin-bottom of 10px, while the text color is set to #9ca3af with a font size of 1rem. </style>

C# Type Class

In C#, the Type class serves as the main avenue for retrieving metadata. It offers functionalities and attributes for examining type details like class name, methods, properties, constructors, base type, and various other aspects.

C# Type Properties

A compilation of key attributes of the Type class is presented here:

Property Description
Assembly It gets the assembly for this type.
AssemblyQualifiedName It gets the assembly-qualified name for this type.
Attributes It gets the attributes associated with the type.
BaseType It gets the base or parent type.
FullName It gets the fully qualified name of the type.
IsAbstract It is used to check if the type is Abstract.
IsArray It is used to check if the type is an Array.
IsClass It is used to check if the type is Class.
IsEnum It is used to check if the type is Enum.
IsInterface It is used to check if the type is an Interface.
IsNested It is used to check if the type is Nested.
IsPrimitive It is used to check if the type is Primitive.
IsPointer It is used to check if the type is Pointer.
IsNotPublic It is used to check if the type is not Public.
IsPublic It is used to check if the type is Public.
IsSealed It is used to check if the type is Sealed.
IsSerializable It is used to check if the type is Serializable.
MemberType It is used to check if the type is a Member type or a Nested type.
Module It gets the module of the type.
Name It gets the name of the type.
Namespace It gets the namespace of the type.

C# Type Methods

A compilation of key functions of the Type class is presented here:

Method Description
GetConstructors() It returns all the public constructors for the Type.
GetConstructors(BindingFlags) It returns all the constructors for the Type with specified BindingFlags.
GetFields() It returns all the public fields for the Type.
GetFields(BindingFlags) It returns all the public constructors for the Type with specified BindingFlags.
GetMembers() It returns all the public members for the Type.
GetMembers(BindingFlags) It returns all the members for the Type with specified BindingFlags.
GetMethods() It returns all the public methods for the Type.
GetMethods(BindingFlags) It returns all the methods for the Type with specified BindingFlags.
GetProperties() It returns all the public properties for the Type.
GetProperties(BindingFlags) It returns all the properties for the Type with specified BindingFlags.
GetType() It gets the current Type.
GetType(String) It gets the Type for the given name.

Types of Reflection in C#

C# primarily offers four different kinds of reflection, as outlined below.

The <style> is styled with a linear gradient background that transitions from #374151 to #1f2937. It has a border-radius of 12px, padding of 40px, and a margin of 20px on the top and bottom. The content is centered within the diagram.

The icon within the <style> has a font size of 3rem and a margin-bottom of 10px, while the text is styled with a color of #9ca3af and a font size of 1rem.

Here, we will explore the various categories of Reflection individually.

1) Type Reflection

In C#, the Type class from the System.Reflection namespace is employed to gather information about a class, including its name, methods, fields, and properties. This can be achieved through the utilization of the GetType method or the typeof operator.

Syntax:

It has the following syntax.

Example

Type typeInfo = typeof(ClassName);

C# Type Reflection Example

Let's consider a scenario to demonstrate retrieving type information using reflection in C#.

Example

Example

using System;

using System.Reflection;

class people

{

    public string name = "John";

    public int age = 20;

    public void Msg()

    {	

        Console.WriteLine("Welcome");

    }

}

class Program

{

    static void Main()

    {

        // Get Type using typeof

        Type type = typeof(people);

        Console.WriteLine("Class Name: " + type.Name);

        // List public fields

        foreach (var field in type.GetFields())

        {

            Console.WriteLine("Field: " + field.Name);

        }

        // List public methods

        foreach (var method in type.GetMethods())

        {

            Console.WriteLine("Method: " + method.Name);

        }

    }

}

Output:

Output

Class Name: people

Field: name

Field: age

Method: Msg

Method: Equals

Method: GetHashCode

Method: GetType

Method: ToString

Explanation:

In this instance, reflection is employed to gather insights regarding the people class. The typeof(people) syntax yields the Type object associated with the class, containing details such as name, fields, and methods. Initially, we display the class name by accessing type.Name. Subsequently, the GetFields function is utilized to showcase all public fields within the class, while GetMethod is employed to reveal all public methods, encompassing both custom and pre-defined methods.

2) Assembly Reflection

In C#, developers can utilize reflection to retrieve details about the assembly in which a class or object is declared. This process is carried out through the System.Reflection namespace, primarily leveraging the Assembly class.

C# Assembly Reflection Example:

Let's consider a scenario to demonstrate the assembly reflection feature in C#.

Example

Example

using System;

using System.Reflection;

class C# Tutorial

{

    public string Name = "John";

    public int Age = 30;

}

class Program

{

    static void Main()

    {

        // Creating an object

        C# Tutorial p = new C# Tutorial();

        Type type = p.GetType();

        Assembly assembly = type.Assembly;

        // Display Assembly information

        Console.WriteLine("Class Name: " + type.Name);

        Console.WriteLine("Assembly Full Name: " + assembly.FullName);

        Console.WriteLine("Assembly Location: " + assembly.Location);

    }

}

Output:

Output

Class Name: C# Tutorial

Assembly Full Name: Main, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

Assembly Location: /tmp/2yFuUluxrd/Main.exe

Explanation:

In this instance, we are demonstrating the use of GetAssembly method to fetch details regarding the assembly. Initially, we instantiate an object named p from the C# Tutorial class, followed by invoking p.GetType to acquire the class's type information. Subsequently, we utilize type.Assembly to retrieve data related to the assembly, including its name and file path.

3) Member Reflection

In C# programming, utilizing member reflection enables developers to dynamically interact with various elements of a class such as methods, fields, properties, and constructors during program execution.

C# Member Reflection Example

Let's consider an example to illustrate member reflection in C#.

Example

Example

using System;

using System.Reflection;

class Tech	

{

    public string Name = "John";

    public void C# Tutorial()

    {

        Console.WriteLine("Welcome, " + Name);

    }

}

class Program

{

    static void Main()

    {

        Tech t = new Tech();

        Type type = t.GetType();

        FieldInfo field = type.GetField("Name");

        field.SetValue(t, "Alice");

        MethodInfo method = type.GetMethod("Hello World");  

        method.Invoke(t, null); 

    }

}

Output:

Output

Welcome, Alice

Explanation:

In this instance, we defined the class names as "Tech" with the field "Name" set to "John" and a method named C# Tutorial responsible for displaying a welcoming message. Within the primary method, we instantiate an object of the "Tech" class. Subsequently, we employ reflection to modify the "Name" field to "Alice". Following this, reflection is utilized to invoke the C# Tutorial method and display the resulting output.

4) Attribute Reflection

In C#, attribute reflection allows us to access metadata added to our code through attributes. This feature enables us to dynamically examine these attributes during runtime, influencing the program's behavior based on this information.

C# Attribute Reflection Example

Let's consider an example to demonstrate attribute reflection in C#.

Example

Example

using System;

using System.Reflection;

[AttributeUsage(AttributeTargets.Method)]

public class LogAttribute : Attribute { }

public class C# Tutorial

{

    [Log]

    public void Message()

    {

        Console.WriteLine("Welcome Welcome Welcome");

    }

}

public class tech

{

    public static void Main()

    {

        MethodInfo mm = typeof(C# Tutorial).GetMethod("Message");

        if (mm.GetCustomAttribute<LogAttribute>() != null)

        {

         Console.WriteLine("The C# Tutorial method has a Log attribute.");

        }

    }

}

Output:

Output

The C# Tutorial method has a Log attribute.

Explanation:

In this instance, we generate a personalized LogAttribute and assign it to a function called Message within the C# Tutorial class. Within the main function, we employ reflection to verify if the Message function has the LogAttribute implemented. When the attribute is detected, the system displays a verification message.

Conclusion

In summary, C# Reflection is an extensive functionality that permits applications to examine and engage with object categories, fields, characteristics, methods, and attributes dynamically. The necessary classes for reflection are housed within the System.Reflection namespace. This capability also grants access to attribute information while the program is running.

C# Reflection FAQs

1) What is Reflection in C#?

In C# programming, reflection refers to the method of detailing type metadata. Necessary classes for reflection are found within the System.Reflection namespace. This functionality permits the retrieval of details regarding classes, methods, properties, and fields.

2) Which namespace is used for reflection in C#?

Within C#, the namespace System.Reflection is responsible for offering a range of classes and methods tailored for the purpose of reflection.

Yes, is it possible to utilize reflection for accessing custom attributes?

Yes, reflection can utilize custom attributes such as retrieving them with GetCustomAttributes or fetching a specific attribute with GetCustomAttribute<T>.

4) What is attribute reflection in C#?

In C#, attribute reflection is a mechanism for accessing metadata that has been incorporated into our code through attributes. By employing reflection, we can examine these attributes during program execution and leverage this data to govern the program's behavior.

5) What is the method to retrieve all attributes of a class through reflection in C#?

In C#, we can access all the public properties of a class by utilizing the GetProperties method provided by the Type class.

Example

PropertyInfo[] properties = typeof(ClassName).GetProperties();

Input Required

This code uses input(). Please provide values below: