Reflection
Inspect type metadata and invoke members at runtime via System.Reflection.
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
LINQ Query
Filter, project, sort, group, and aggregate sequences with LINQ.
Async and Await
Run I/O concurrently with async methods, await, and Task.WhenAll.
Properties
Encapsulate state with auto, computed, validated, and init-only properties.
Generics
Write type-parameterized methods and classes with constraints.
Delegates and Events
Define delegate types and publish events with safe subscription.
Collections
Use List, Dictionary, HashSet, Queue, Stack, and read-only views.