.NET HELP

C# Reflection (How It Works For Developers)

Published January 27, 2024
Share:

In the world of software development, C# is a versatile and powerful programming language that provides a wide range of features to developers.

One such feature that stands out for its flexibility and dynamism is reflection. Reflection in C# allows developers to inspect and interact with the metadata of types during runtime. This capability opens up a new dimension of possibilities, enabling developers to create more flexible, extensible, and robust applications.

In this article, we'll delve into the intricacies of C# reflection, exploring its key concepts, use cases, and best practices. We will also find the reflection information of the PdfDocument object of IronPDF.

Reflection in C#

Reflection is a mechanism that allows a program to examine and manipulate its structure and behavior at runtime. In C#, this is achieved through the System.Reflection namespace which provides classes and methods for interacting with metadata, obtaining information about types, and even creating instances dynamically.

Key Components of Reflection

Type Class

At the core of C# reflection is the Type class, which represents a type in the .NET runtime. This class provides a wealth of information about a type, including all the public methods, properties, fields, events, and method parameters.

You can obtain a Type object for a given type using various methods, such as the typeof() operator or by calling the GetType() method on an object.

using System;

class Program
{
    static void Main()
    {
        // Using typeof to get Type information for string
        Type stringType = typeof(string);
        Console.WriteLine("Information about the string type:");
        Console.WriteLine($"Type Name: {stringType.Name}");
        Console.WriteLine($"Full Name: {stringType.FullName}");
        Console.WriteLine($"Assembly Qualified Name: {stringType.AssemblyQualifiedName}");
    }
}
using System;

class Program
{
    static void Main()
    {
        // Using typeof to get Type information for string
        Type stringType = typeof(string);
        Console.WriteLine("Information about the string type:");
        Console.WriteLine($"Type Name: {stringType.Name}");
        Console.WriteLine($"Full Name: {stringType.FullName}");
        Console.WriteLine($"Assembly Qualified Name: {stringType.AssemblyQualifiedName}");
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		' Using typeof to get Type information for string
		Dim stringType As Type = GetType(String)
		Console.WriteLine("Information about the string type:")
		Console.WriteLine($"Type Name: {stringType.Name}")
		Console.WriteLine($"Full Name: {stringType.FullName}")
		Console.WriteLine($"Assembly Qualified Name: {stringType.AssemblyQualifiedName}")
	End Sub
End Class
VB   C#

Output

C# Reflection (How It Works For Developer): Figure 1

Assembly Class

An assembly in .NET is a unit of deployment and versioning. The Assembly class in the System.Reflection namespace provides methods to load and describe assemblies and inspect assembly info dynamically.

You can obtain an Assembly object for any instance of the currently executing assembly or for any referenced assembly.

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // Example 1: Get information about the executing assembly
        Assembly executingAssembly = Assembly.GetExecutingAssembly();
        Console.WriteLine("Information about the executing assembly:");
        DisplayAssemblyInfo(executingAssembly);

        // Example 2: Load the mscorlib assembly
        Assembly mscorlibAssembly = Assembly.Load("mscorlib");
        Console.WriteLine("\nInformation about the mscorlib assembly:");
        DisplayAssemblyInfo(mscorlibAssembly);
    }

    static void DisplayAssemblyInfo(Assembly assembly)
    {
        Console.WriteLine($"Assembly Name: {assembly.GetName().Name}");
        Console.WriteLine($"Full Name: {assembly.FullName}");
        Console.WriteLine($"Location: {assembly.Location}");
        Console.WriteLine("\nModules:");

        foreach (var module in assembly.GetModules())
        {
            Console.WriteLine($"- {module.Name}");
        }

        Console.WriteLine(new string('-', 30));
    }
}
using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // Example 1: Get information about the executing assembly
        Assembly executingAssembly = Assembly.GetExecutingAssembly();
        Console.WriteLine("Information about the executing assembly:");
        DisplayAssemblyInfo(executingAssembly);

        // Example 2: Load the mscorlib assembly
        Assembly mscorlibAssembly = Assembly.Load("mscorlib");
        Console.WriteLine("\nInformation about the mscorlib assembly:");
        DisplayAssemblyInfo(mscorlibAssembly);
    }

    static void DisplayAssemblyInfo(Assembly assembly)
    {
        Console.WriteLine($"Assembly Name: {assembly.GetName().Name}");
        Console.WriteLine($"Full Name: {assembly.FullName}");
        Console.WriteLine($"Location: {assembly.Location}");
        Console.WriteLine("\nModules:");

        foreach (var module in assembly.GetModules())
        {
            Console.WriteLine($"- {module.Name}");
        }

        Console.WriteLine(new string('-', 30));
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Reflection

Friend Class Program
	Shared Sub Main()
		' Example 1: Get information about the executing assembly
		Dim executingAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
		Console.WriteLine("Information about the executing assembly:")
		DisplayAssemblyInfo(executingAssembly)

		' Example 2: Load the mscorlib assembly
		Dim mscorlibAssembly As System.Reflection.Assembly = System.Reflection.Assembly.Load("mscorlib")
		Console.WriteLine(vbLf & "Information about the mscorlib assembly:")
		DisplayAssemblyInfo(mscorlibAssembly)
	End Sub

	Private Shared Sub DisplayAssemblyInfo(ByVal assembly As System.Reflection.Assembly)
		Console.WriteLine($"Assembly Name: {assembly.GetName().Name}")
		Console.WriteLine($"Full Name: {assembly.FullName}")
		Console.WriteLine($"Location: {assembly.Location}")
		Console.WriteLine(vbLf & "Modules:")

		For Each [module] In assembly.GetModules()
			Console.WriteLine($"- {[module].Name}")
		Next [module]

		Console.WriteLine(New String("-"c, 30))
	End Sub
End Class
VB   C#

Output

C# Reflection (How It Works For Developer): Figure 2

MethodInfo, PropertyInfo, FieldInfo, and EventInfo Classes

These classes represent public members, methods, properties, fields, and events, respectively. They expose information about these members, such as their names, types, accessibility, and more.

You can obtain access to instances of these classes through the Type class.

using System;
using System.Reflection;

class MyClass
{
    public void MyMethod() { }
    public int MyProperty { get; set; }
    public string myField;
    public event EventHandler MyEvent;
}

class Program
{
    static void Main()
    {
        // Get MethodInfo for MyMethod
        MethodInfo methodInfo = typeof(MyClass).GetMethod("MyMethod");
        Console.WriteLine($"Method Name: {methodInfo.Name}");

        // Get PropertyInfo for MyProperty
        PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty");
        Console.WriteLine($"Property Name: {propertyInfo.Name}");

        // Get FieldInfo for myField
        FieldInfo fieldInfo = typeof(MyClass).GetField("myField");
        Console.WriteLine($"Field Name: {fieldInfo.Name}");

        // Get EventInfo for MyEvent
        EventInfo eventInfo = typeof(MyClass).GetEvent("MyEvent");
        Console.WriteLine($"Event Name: {eventInfo.Name}");
    }
}
using System;
using System.Reflection;

class MyClass
{
    public void MyMethod() { }
    public int MyProperty { get; set; }
    public string myField;
    public event EventHandler MyEvent;
}

class Program
{
    static void Main()
    {
        // Get MethodInfo for MyMethod
        MethodInfo methodInfo = typeof(MyClass).GetMethod("MyMethod");
        Console.WriteLine($"Method Name: {methodInfo.Name}");

        // Get PropertyInfo for MyProperty
        PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty");
        Console.WriteLine($"Property Name: {propertyInfo.Name}");

        // Get FieldInfo for myField
        FieldInfo fieldInfo = typeof(MyClass).GetField("myField");
        Console.WriteLine($"Field Name: {fieldInfo.Name}");

        // Get EventInfo for MyEvent
        EventInfo eventInfo = typeof(MyClass).GetEvent("MyEvent");
        Console.WriteLine($"Event Name: {eventInfo.Name}");
    }
}
Imports System
Imports System.Reflection

Friend Class [MyClass]
	Public Sub MyMethod()
	End Sub
	Public Property MyProperty() As Integer
	Public myField As String
	Public Event MyEvent As EventHandler
End Class

Friend Class Program
	Shared Sub Main()
		' Get MethodInfo for MyMethod
		Dim methodInfo As MethodInfo = GetType([MyClass]).GetMethod("MyMethod")
		Console.WriteLine($"Method Name: {methodInfo.Name}")

		' Get PropertyInfo for MyProperty
		Dim propertyInfo As PropertyInfo = GetType([MyClass]).GetProperty("MyProperty")
		Console.WriteLine($"Property Name: {propertyInfo.Name}")

		' Get FieldInfo for myField
		Dim fieldInfo As FieldInfo = GetType([MyClass]).GetField("myField")
		Console.WriteLine($"Field Name: {fieldInfo.Name}")

		' Get EventInfo for MyEvent
		Dim eventInfo As EventInfo = GetType([MyClass]).GetEvent("MyEvent")
		Console.WriteLine($"Event Name: {eventInfo.Name}")
	End Sub
End Class
VB   C#

Output

C# Reflection (How It Works For Developer): Figure 3

Introducing IronPDF

IronPDF - Official Website is a powerful C# library that provides a comprehensive set of features for working with PDF documents in .NET applications. It allows developers to easily create, manipulate, and extract data from an existing object such as PDF files using a simple and intuitive API.

One notable feature of IronPDF is its ability to seamlessly integrate with existing C# projects, making it an excellent choice for adding PDF generation and manipulation capabilities.

Key Features of IronPDF

Some key features of IronPDF are as follows:

  1. PDF Generation: Easily generate PDF documents from scratch or convert HTML, images, and other formats into PDF.
  2. PDF Manipulation: Edit existing PDFs by adding, removing, or modifying text, images, and annotations.
  3. PDF Extraction: Extract text, images, and metadata from PDF files for further processing.
  4. HTML to PDF Conversion: Convert HTML content, including CSS and JavaScript, into high-quality PDFs.
  5. PDF Forms: Create and fill interactive PDF forms programmatically.
  6. Security: Apply encryption and password protection to secure PDF documents.

Now, let's explore how to use C# reflection with IronPDF in a detailed code example.

Using C# Reflection with IronPDF

In this simple example, we'll get the information about the IronPDF PDF document object using C# reflection.

Install IronPDF NuGet Package

Make sure to install the IronPDF NuGet package into your project. You can do this using the NuGet Package Manager Console:

Install-Package IronPdf

Using C# Reflection to get data of IronPDF PDF Document Object

using IronPdf;
using System;

Type PDF = typeof(PdfDocument);
Console.WriteLine("Information about the PdfDocument type:");
Console.WriteLine($"Type Name: {PDF.Name}");
Console.WriteLine($"Full Name: {PDF.FullName}");
Console.WriteLine($"Assembly Qualified Name: {PDF.AssemblyQualifiedName}");
Console.WriteLine("\nMembers:");
foreach (var memberInfo in PDF.GetMembers())
{
    Console.WriteLine($"{memberInfo.MemberType} {memberInfo.Name}");
}
using IronPdf;
using System;

Type PDF = typeof(PdfDocument);
Console.WriteLine("Information about the PdfDocument type:");
Console.WriteLine($"Type Name: {PDF.Name}");
Console.WriteLine($"Full Name: {PDF.FullName}");
Console.WriteLine($"Assembly Qualified Name: {PDF.AssemblyQualifiedName}");
Console.WriteLine("\nMembers:");
foreach (var memberInfo in PDF.GetMembers())
{
    Console.WriteLine($"{memberInfo.MemberType} {memberInfo.Name}");
}
Imports Microsoft.VisualBasic
Imports IronPdf
Imports System

Private PDF As Type = GetType(PdfDocument)
Console.WriteLine("Information about the PdfDocument type:")
Console.WriteLine($"Type Name: {PDF.Name}")
Console.WriteLine($"Full Name: {PDF.FullName}")
Console.WriteLine($"Assembly Qualified Name: {PDF.AssemblyQualifiedName}")
Console.WriteLine(vbLf & "Members:")
For Each memberInfo In PDF.GetMembers()
	Console.WriteLine($"{memberInfo.MemberType} {memberInfo.Name}")
Next memberInfo
VB   C#

The provided C# code utilizes reflection to obtain information about the PdfDocument type from the IronPDF library. Initially, the typeof(PdfDocument) expression is used to retrieve the Type object representing the PdfDocument type.

Subsequently, various properties of the obtained Type object are printed to the console, including the type name, full name, and assembly-qualified name.

Additionally, the code utilizes a foreach loop to iterate through the members of the PdfDocument type, printing information about each member, such as its member type and name.

This approach showcases the use of reflection to dynamically inspect the structure and metadata of objects of the PdfDocument type during runtime, providing insights into the composition and all the public members of the IronPDF library's PdfDocument class.

Output:

C# Reflection (How It Works For Developer): Figure 4

Conclusion

C# reflection is a powerful mechanism that empowers developers to dynamically inspect and manipulate the structure of types at runtime.

This article has explored key concepts, use cases, and best practices associated with C# reflection, highlighting its significance in creating flexible and extensible applications.

Additionally, the integration of IronPDF, a robust PDF manipulation library, further demonstrates the versatility of C# reflection in obtaining information about the PdfDocument type dynamically.

As developers leverage these capabilities, they gain the flexibility to adapt their applications to changing requirements and scenarios, showcasing the dynamic nature of C# and the valuable contributions of libraries like IronPDF in enhancing document processing capabilities.

IronPDF is a well-documented library with many tutorials. To see the tutorials, visit IronPDF Tutorial Documentation, which provides a greater opportunity for developers to learn about its features.

< PREVIOUS
NPlot C# (How It Works For Developers)
NEXT >
Npgsql C# .NET (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,781,565 View Licenses >