Reflection lets a program look at its own parts while running. Why might this be useful?
Think about when you want to learn about an object without knowing its details before running the program.
Reflection allows a program to inspect objects, types, and members during execution. This helps when you don't know the exact types or properties beforehand.
What will this C# code print?
using System; using System.Reflection; class Person { public string Name { get; set; } = "Alice"; public int Age { get; set; } = 30; } class Program { static void Main() { Person p = new Person(); Type t = p.GetType(); foreach (PropertyInfo prop in t.GetProperties()) { Console.WriteLine($"{prop.Name}: {prop.GetValue(p)}"); } } }
Look at how reflection gets property names and values from the object.
The code uses reflection to get all properties of the Person object and prints their names and current values. Since Name is "Alice" and Age is 30, it prints those.
What error does this code cause and why?
using System; using System.Reflection; class Program { static void Main() { Type t = Type.GetType("NonExistentClass"); Console.WriteLine(t.Name); } }
What happens if Type.GetType cannot find the class?
Type.GetType returns null if the class is not found. Then accessing t.Name causes a NullReferenceException.
Which option correctly gets the MethodInfo for a method named 'Calculate' in class 'MathOps'?
class MathOps { public int Calculate(int x) { return x * 2; } }
Remember to use typeof and pass the method name as a string.
typeof(MathOps) gets the Type object. GetMethod requires the method name as a string. Options A and B are invalid because MathOps is used directly and is not a Type object. Option C misses quotes around method name. D is correct.
Given this code, what is the output?
using System; using System.Reflection; class Greeter { public void SayHello(string name) { Console.WriteLine($"Hello, {name}!"); } } class Program { static void Main() { Greeter g = new Greeter(); MethodInfo mi = typeof(Greeter).GetMethod("SayHello"); mi.Invoke(g, new object[] { "Bob" }); } }
Check how Invoke passes parameters as an object array.
The code uses reflection to find the method SayHello and calls it on the Greeter object with parameter "Bob". It prints 'Hello, Bob!'.