Skip to content
C#

Reflection

Inspect type metadata and invoke members at runtime via System.Reflection.

By EZ4Code Team
reflectionmetadataattributes

Code

using System;
using System.Reflection;

public class Sample
{
    public string Name { get; set; } = "";
    public int Age { get; set; }

    [Obsolete("Use Process2")]
    public void Process() => Console.WriteLine("Process");
}

class Program
{
    static void Main()
    {
        var type = typeof(Sample);

        Console.WriteLine($"Type: {type.Name}");
        Console.WriteLine("Properties:");
        foreach (var p in type.GetProperties())
            Console.WriteLine($"  {p.PropertyType.Name} {p.Name}");

        Console.WriteLine("Methods:");
        foreach (var m in type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
            Console.WriteLine($"  {m.ReturnType.Name} {m.Name}()");

        // Instantiate and invoke
        var instance = Activator.CreateInstance<Sample>();
        type.GetProperty("Name")!.SetValue(instance, "Alice");
        type.GetMethod("Process")!.Invoke(instance, null);

        // Read attribute
        var attr = type.GetMethod("Process")!.GetCustomAttribute<ObsoleteAttribute>();
        Console.WriteLine($"Obsolete? {attr is not null}");
    }
}

Explanation

Reflection inspects type metadata at runtime: properties, methods, attributes, and constructors. typeof and GetType return a Type object you can query, and Activator.CreateInstance builds objects without compile-time references. Combined with attributes, this powers serialization, validation, and dependency injection frameworks.

More C# Snippets