Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. C#
  4. Understanding Reflection in C#

Understanding Reflection in C#

Date- Mar 16,2026 44
c# reflection

Overview of Reflection

Reflection in C# is a powerful feature that allows you to inspect and interact with object types and their members at runtime. This capability is significant because it enables developers to create flexible and dynamic applications, where types can be discovered and manipulated without prior knowledge of their structure. Reflection is particularly useful in scenarios such as serialization, dependency injection, and creating plugins.

Prerequisites

  • Basic understanding of C# syntax
  • Familiarity with classes and objects
  • Knowledge of .NET Framework or .NET Core
  • Experience with Visual Studio or other C# IDEs

Using Reflection to Inspect Types

Reflection allows you to inspect the metadata of types, including properties, methods, and events. This section demonstrates how to retrieve information about a class using reflection.

using System;
using System.Reflection;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void Greet()
    {
        Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
    }
}

class Program
{
    static void Main()
    {
        Type personType = typeof(Person);

        Console.WriteLine($"Class Name: {personType.Name}");

        PropertyInfo[] properties = personType.GetProperties();
        Console.WriteLine("Properties:");
        foreach (var property in properties)
        {
            Console.WriteLine($"- {property.Name} ({property.PropertyType})");
        }

        MethodInfo[] methods = personType.GetMethods();
        Console.WriteLine("Methods:");
        foreach (var method in methods)
        {
            Console.WriteLine($"- {method.Name}");
        }
    }
} 

This code defines a Person class with properties and a method. In the Program class, we use reflection to inspect the Person type:

  • Type personType = typeof(Person); - This line retrieves the Type object representing the Person class.
  • Console.WriteLine($"Class Name: {personType.Name}"); - Outputs the name of the class.
  • PropertyInfo[] properties = personType.GetProperties(); - Gets an array of PropertyInfo objects representing the properties of the class.
  • foreach (var property in properties) - Iterates through each property to output its name and type.
  • MethodInfo[] methods = personType.GetMethods(); - Retrieves an array of MethodInfo objects for the class methods.
  • foreach (var method in methods) - Iterates through each method to output its name.

Creating Instances Dynamically

Reflection not only allows you to inspect types but also to create instances of them dynamically. This section shows how to instantiate a class without knowing its type at compile time.

using System;
using System.Reflection;

class Animal
{
    public string Species { get; set; }
    public void Speak()
    {
        Console.WriteLine($"{Species} makes a noise.");
    }
}

class Program
{
    static void Main()
    {
        Type animalType = typeof(Animal);
        object animalInstance = Activator.CreateInstance(animalType);

        PropertyInfo speciesProperty = animalType.GetProperty("Species");
        speciesProperty.SetValue(animalInstance, "Dog");

        MethodInfo speakMethod = animalType.GetMethod("Speak");
        speakMethod.Invoke(animalInstance, null);
    }
} 

In this example, we define an Animal class and create an instance of it using reflection:

  • object animalInstance = Activator.CreateInstance(animalType); - Creates an instance of the Animal class dynamically.
  • PropertyInfo speciesProperty = animalType.GetProperty("Species"); - Retrieves the PropertyInfo for the Species property.
  • speciesProperty.SetValue(animalInstance, "Dog"); - Sets the Species property of the newly created instance to "Dog".
  • MethodInfo speakMethod = animalType.GetMethod("Speak"); - Retrieves the MethodInfo for the Speak method.
  • speakMethod.Invoke(animalInstance, null); - Invokes the Speak method on the animal instance, which outputs the appropriate message.

Accessing Private Members

Reflection can also be used to access private members of a class, which is useful for testing and debugging. This section illustrates how to get and set private fields.

using System;
using System.Reflection;

class Secret
{
    private string password = "hidden";
}

class Program
{
    static void Main()
    {
        Secret secret = new Secret();
        Type secretType = secret.GetType();

        FieldInfo passwordField = secretType.GetField("password", BindingFlags.NonPublic | BindingFlags.Instance);
        Console.WriteLine($"Original Password: {passwordField.GetValue(secret)}");

        passwordField.SetValue(secret, "newpassword");
        Console.WriteLine($"Updated Password: {passwordField.GetValue(secret)}");
    }
} 

In this example, we use reflection to access a private field in the Secret class:

  • FieldInfo passwordField = secretType.GetField("password", BindingFlags.NonPublic | BindingFlags.Instance); - Retrieves the FieldInfo for the private password field of the Secret class.
  • passwordField.GetValue(secret) - Gets the current value of the password field.
  • passwordField.SetValue(secret, "newpassword"); - Sets a new value for the password field.

Best Practices and Common Mistakes

While reflection is a powerful tool, it should be used judiciously. Here are some best practices and common mistakes to avoid:

  • Use reflection sparingly: Since reflection can introduce performance overhead, it should only be used when necessary.
  • Cache type information: If you need to access types frequently, cache the type information instead of retrieving it multiple times.
  • Avoid accessing private members unnecessarily: Accessing private members can break encapsulation. Use reflection for testing or debugging, but avoid it in production code.
  • Handle exceptions: Reflection can throw exceptions, so always handle potential exceptions when using reflection.

Conclusion

In summary, reflection in C# is a powerful feature that allows for dynamic type inspection and interaction. We explored how to inspect types, create instances dynamically, and access private members using reflection. Remember to use reflection judiciously and follow best practices to avoid potential pitfalls. With a solid understanding of reflection, you can enhance the flexibility and functionality of your C# applications.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Understanding Memory Management and Garbage Collection in .NET
Mar 16, 2026
Introduction to C# Programming: Your First Steps in Software Development
Mar 08, 2026
Understanding Extension Methods in C#: Enhancing Your Code with Ease
Mar 16, 2026
Mastering Design Patterns in C#: Singleton, Factory, and Observer
Mar 16, 2026
Previous in C#
Mastering File I/O in C#: A Comprehensive Guide to Reading and Wr…
Next in C#
Mastering Unit Testing with xUnit in .NET: A Comprehensive Guide
Buy me a pizza

Comments

On this page

🎯

Interview Prep

Ace your C# interview with curated Q&As for all levels.

View C# Interview Q&As

More in C#

  • Zoom C# Wrapper Integration 12905 views
  • Convert HTML String To Image In C# 11504 views
  • The report definition is not valid or is not supported by th… 10856 views
  • Replacing Accent Characters with Alphabet Characters in CSha… 9843 views
  • Get IP address using c# 8689 views
View all C# posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor