Skip to content

Latest commit

 

History

History

README.md

ReflectionExamples - .NET Reflection Examples and Benchmarks

YouTube Blog Newsletter All Links LinkedIn

This solution is a comprehensive collection of C# reflection examples covering discovery, attribute scanning, non-public member access, and performance benchmarking. It provides five separate projects that progressively explore the capabilities and trade-offs of reflection in .NET.

CheckMembers lists all constructors, properties, and methods of a class with parameter details. ExampleAppAttributes demonstrates custom attribute scanning across assemblies using [MyClassAttribute] and [MyMethodAttribute]. ExampleAppGetByName provides an interactive CLI for searching types by substring and inspecting their public and non-public members. NonPublic shows how to access private constructors, invoke private methods, and set private field values using reflection, demonstrating reflection's ability to bypass access modifiers. ActivatorVsInvokeMemberBenchmarks uses BenchmarkDotNet to compare five different reflection-based instantiation techniques — direct constructor calls, Activator.CreateInstance(), Type.InvokeMember(), and ConstructorInfo.Invoke() — across parameterless, classic, and primary constructor classes.

These examples are paired with Dev Leader blog content and serve as practical references for understanding when and how to use reflection effectively in C# applications.

Getting Started

Prerequisites

  • .NET 8.0 SDK or later
  • An IDE such as Visual Studio, Visual Studio Code, or JetBrains Rider

Running the Project

# Run the member discovery example
dotnet run --project ReflectionExamples.CheckMembers

# Run the attribute scanning example
dotnet run --project ReflectionExamples.ExampleAppAttributes

# Run the interactive type search
dotnet run --project ReflectionExamples.ExampleAppGetByName

# Run the non-public member access example
dotnet run --project ReflectionExamples.NonPublic

# Run the performance benchmarks (use Release mode)
dotnet run -c Release --project ReflectionExamples.ActivatorVsInvokeMemberBenchmarks

Related Resources

Blog Articles

Newsletter

If you found this useful and you want to learn more about C#, .NET, and software engineering, subscribe to the free Dev Leader Weekly newsletter:

Subscribe to Dev Leader Weekly

Connect with Dev Leader


BrandGhost

Powered by BrandGhost 👻