Lesson 24/30

Tutorials C# Mastery

Reflection and Attributes: Reading Metadata at Runtime

On this page

Reflection & Metadata

Reflection is the ability of your program to "look in the mirror" and inspect its own code structure at runtime. While it is incredibly powerful for building frameworks (like Dependency Injection containers or JSON Serializers), it carries a heavy performance cost and must be used with caution.

1. Inspecting Types

You can discover properties, methods, and private fields of any object even if you've never seen the class before.

var user = new User();
Type type = user.GetType();

foreach(var prop in type.GetProperties()) 
{
    Console.WriteLine($"Found Property: {prop.Name}");
}

2. Attributes: The "Stickers" of C#

Attributes allow you to tag your code with extra information (Metadata) that can be read later by Reflection.

[Serializable]
[Author("Sandeep")]
public class Order { ... }

3. The Performance Tax

Reflection is slow because the CLR has to scan the assembly metadata and resolve strings into memory pointers manually. A method call via Reflection can be 100x slower than a direct method call.

4. Interview Mastery

Q: "If Reflection is so slow, how do high-performance frameworks like AutoMapper or JSON.NET work so fast?"

Architect Answer: "The secret is 'Emit' and 'Caching.' A professional framework uses Reflection exactly ONCE to inspect the type. Then, it uses `System.Reflection.Emit` to generate raw IL (Intermediate Language) code in memory essentially writing a new C# class dynamically that performs the mapping. This new dynamic class is then cached. All subsequent calls bypass Reflection entirely and run as native, top-speed compiled code."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

C# Mastery
Course syllabus
1. Modern C# & Framework Fundamentals
2. Control Flow & Logical Structures
3. Object-Oriented Mastery
4. Functional C# & Collections
5. Asynchronous & Parallel Programming
6. Advanced Engineering & High Performance
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details