Reflection
By the end of this lesson you'll be able to inspect any type's structure at runtime — its properties, methods, and fields — read and set values by name, invoke methods and build objects dynamically, and read custom attributes. This is the machinery behind frameworks like ASP.NET, Entity Framework, and JSON serializers.
Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.
Part of the free C# course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Reflection is an X-ray for your code . Normally you interact with an object through its public buttons and levers — you call person.Greet() because you wrote that line knowing it exists. Reflection lets a program take an X-ray of a type it has never seen before: it can see every property, every method, every field — even the private ones tucked inside — and then act on what it finds. That's how a JSON serializer turns any object into text without you writing code for each class, and how a test runner discovers every method marked [Test] . The program inspects a type's own structure at runtime and reacts to it.
Reflection lives in the System.Reflection namespace and revolves around a family of "info" objects. Each one describes one piece of a type. Once you have a Type , everything else hangs off it.
By default, GetProperties() and friends return only the public instance members. To reach private or static members you must pass BindingFlags (covered in section 1).
1. Inspecting a Type
Everything starts with a Type object — the runtime's description of a class. Use typeof(Person) when you know the type at compile time, or obj.GetType() when you only have an instance. From a Type you can call GetProperties() , GetMethods() , and GetFields() to list its members. By default those see only public members; to include private ones you pass BindingFlags — a set of switches like Public | NonPublic | Instance . Read this worked example, run it, then you'll write your own loop.
Your turn. The program below gets a Type and loops over its properties — you just need to fill in how to get the type and how to print each property's name. Fill in the three ___ blanks, then run it.
2. Reading Values, Invoking Methods & Creating Objects
Inspecting structure is half the story — reflection also lets you act on an instance by name. PropertyInfo.GetValue(obj) reads a property's value and SetValue(obj, value) writes it. MethodInfo.Invoke(obj, args) calls a method, with the arguments packed into an object[] (use null for none). And Activator.CreateInstance(type) builds an object without writing new — the trick that powers plugin systems that discover types at runtime. Read this worked example, then you'll wire up your own.
Now you try. Read a property value off an instance, find a method by name, and invoke it with one argument. Fill in the three ___ blanks:
If GetMethod("Think") returns null for a method you know exists, the culprit is almost always visibility. The no-argument overloads return only public instance members. To reach anything else you must combine BindingFlags with a bitwise OR ( | ):
Rule of thumb: you almost always need at least one of Instance or Static , plus at least one of Public or NonPublic . Forget the visibility pair and you'll silently get nothing back.
3. Custom Attributes
Attributes are metadata tags you attach to code in [Square brackets] . You define your own by extending Attribute , apply it to a class, method, or property, then read it back at runtime with GetCustomAttribute<T>() . This is the engine behind so much of .NET: ASP.NET discovers routes from [HttpGet] , EF Core maps columns from [Required] , and serializers skip fields marked [JsonIgnore] . The framework uses reflection to find your tags and act on them.
Q: What's the difference between typeof and GetType() ?
typeof(Person) works at compile time when you already know the type. obj.GetType() works at runtime on an instance and returns the object's actual type — which may be a subclass. If Animal a = new Dog(); , then typeof(Animal) is Animal but a.GetType() is Dog.
Q: Why is my private method or field invisible to reflection?
The default GetMethod / GetField only returns public members. Add BindingFlags.NonPublic | BindingFlags.Instance (plus Static for static members) to the call to reach private ones.
For occasional use — startup, configuration, a one-off scan — it's fine. In a tight loop it's a problem: it can be 10–100× slower than a direct call. Cache the PropertyInfo / MethodInfo outside the loop, or switch to source generators or compiled delegates for hot paths.
Q: Why did Invoke throw a TargetInvocationException instead of the real error?
When the method you invoked throws, reflection wraps that exception in a TargetInvocationException . The original error is in its InnerException — inspect that to see what actually went wrong.
No blanks this time — just a brief and an outline. Write a Dump(object obj) method that uses reflection to print every public property of any object as Name = Value — the same trick a debugger or serializer uses. Run it on the Product and check your output against the expected lines in the comments.
Practice quiz
How do you get a Type object at compile time when you already know the type?
- obj.GetType()
- Type.From(Person)
- typeof(Person)
- new Type(Person)
Answer: typeof(Person). typeof(T) gets the Type at compile time; obj.GetType() is for when you only have an instance.
By default, what members does Type.GetProperties() return?
- Only public instance members
- All members including private
- Only static members
- Nothing until you pass BindingFlags
Answer: Only public instance members. Without BindingFlags, the no-argument overloads return only public instance members.
Which BindingFlags combination is needed to see a private instance method?
- Public | Instance
- Public | Static
- NonPublic | Static
- NonPublic | Instance
Answer: NonPublic | Instance. To reach a private instance member you need NonPublic plus Instance.
What does Activator.CreateInstance(type) do?
- Returns the Type's name
- Creates an object without writing 'new'
- Lists the type's properties
- Reads a property value
Answer: Creates an object without writing 'new'. Activator.CreateInstance builds an object dynamically, calling the parameterless constructor.
Which method reads a property's value off an instance via reflection?
- prop.GetValue(obj)
- prop.SetValue(obj)
- prop.Invoke(obj)
- prop.ReadValue(obj)
Answer: prop.GetValue(obj). PropertyInfo.GetValue(obj) reads a property's value; SetValue writes it.
When invoking a method with MethodInfo.Invoke, how are the arguments passed?
- As named parameters
- As a comma-separated string