Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Why reflection is needed in C Sharp (C#) - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Reflection Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use reflection in C#?

Reflection lets a program look at its own parts while running. Why might this be useful?

ATo find out the names and types of properties in an object at runtime
BTo permanently change the source code of a program
CTo speed up the program by avoiding method calls
DTo make the program run without any errors
Attempts:
2 left
💡 Hint

Think about when you want to learn about an object without knowing its details before running the program.

❓ Predict Output
intermediate
2:00remaining
Output of reflection code

What will this C# code print?

C Sharp (C#)
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)}");
        }
    }
}
A
Name: Alice
Age: 30
BCompilation error
C
Name: Alice
Age: 0
D
Name: 
Age: 0
Attempts:
2 left
💡 Hint

Look at how reflection gets property names and values from the object.

🔧 Debug
advanced
2:00remaining
Why does this reflection code throw an exception?

What error does this code cause and why?

C Sharp (C#)
using System;
using System.Reflection;

class Program {
    static void Main() {
        Type t = Type.GetType("NonExistentClass");
        Console.WriteLine(t.Name);
    }
}
ANo error, prints 'NonExistentClass'
BTypeLoadException because the class does not exist
CCompilation error because NonExistentClass is undefined
DNullReferenceException because Type.GetType returned null
Attempts:
2 left
💡 Hint

What happens if Type.GetType cannot find the class?

📝 Syntax
advanced
2:00remaining
Correct way to get method info using reflection

Which option correctly gets the MethodInfo for a method named 'Calculate' in class 'MathOps'?

C Sharp (C#)
class MathOps {
    public int Calculate(int x) { return x * 2; }
}
AMathOps.GetMethod(Calculate)
BMathOps.GetMethod("Calculate")
Ctypeof(MathOps).GetMethod("Calculate")
Dtypeof(MathOps).GetMethod(Calculate)
Attempts:
2 left
💡 Hint

Remember to use typeof and pass the method name as a string.

🚀 Application
expert
3:00remaining
Using reflection to invoke a method dynamically

Given this code, what is the output?

C Sharp (C#)
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" });
    }
}
AHello, name!
BHello, Bob!
CRuntime error: TargetParameterCountException
DCompilation error
Attempts:
2 left
💡 Hint

Check how Invoke passes parameters as an object array.

Practice

(1/5)
1. Why do programmers use reflection in C#?
easy
A. To manage memory manually
B. To write faster code by avoiding loops
C. To examine and use information about types at runtime
D. To create graphical user interfaces

Solution

  1. Step 1: Understand what reflection does

    Reflection allows a program to look at its own structure, like classes and methods, while it is running.
  2. Step 2: Identify the purpose of reflection

    It is used to examine and interact with types dynamically, not for speed or UI creation.
  3. Final Answer:

    To examine and use information about types at runtime -> Option C
  4. Quick Check:

    Reflection = runtime type info [OK]
Hint: Reflection inspects types during program run [OK]
Common Mistakes:
  • Confusing reflection with UI design
  • Thinking reflection speeds up code
  • Believing reflection manages memory
2. Which of the following is the correct way to get the type of an object obj using reflection in C#?
easy
A. Type t = obj.GetType();
B. Type t = GetType(obj);
C. Type t = typeof(obj);
D. Type t = obj.Type();

Solution

  1. Step 1: Recall the method to get an object's type

    In C#, the method GetType() is called on the object instance to get its type.
  2. Step 2: Check each option's syntax

    Type t = obj.GetType(); uses obj.GetType(), which is correct. Type t = GetType(obj); and D are invalid syntax. Type t = typeof(obj); uses typeof incorrectly because it expects a type name, not an object.
  3. Final Answer:

    Type t = obj.GetType(); -> Option A
  4. Quick Check:

    obj.GetType() gets type [OK]
Hint: Use obj.GetType() to get runtime type [OK]
Common Mistakes:
  • Using typeof with an object instance
  • Calling non-existent methods like obj.Type()
  • Trying to pass object to GetType as argument
3. What will be the output of this C# code?
using System;
class Program {
  static void Main() {
    var type = typeof(string);
    Console.WriteLine(type.Name);
  }
}
medium
A. string
B. String
C. System.String
D. Type

Solution

  1. Step 1: Understand typeof operator

    typeof(string) returns the Type object for the string class.
  2. Step 2: Check what type.Name returns

    The Name property returns the class name without namespace, which is "String" with capital S.
  3. Final Answer:

    String -> Option B
  4. Quick Check:

    typeof(string).Name = "String" [OK]
Hint: typeof(T).Name returns class name without namespace [OK]
Common Mistakes:
  • Confusing lowercase 'string' keyword with class name
  • Expecting full namespace in Name property
  • Thinking output is 'Type'
4. Identify the error in this reflection code snippet:
Type t = typeof(int);
var method = t.GetMethod("Parse");
int result = method.Invoke(null, new object[] { "123" });
Console.WriteLine(result);
medium
A. Invoke returns object, needs casting to int
B. GetMethod("Parse") does not exist on int
C. typeof(int) should be typeof(Int32)
D. Invoke cannot be called with null as first argument

Solution

  1. Step 1: Check method retrieval

    int (System.Int32) has a static method "Parse", so GetMethod("Parse") works.
  2. Step 2: Check Invoke return type and usage

    Invoke returns an object. Assigning it directly to int causes a compile error. It needs explicit cast: (int)method.Invoke(...).
  3. Final Answer:

    Invoke returns object, needs casting to int -> Option A
  4. Quick Check:

    Invoke returns object, cast needed [OK]
Hint: Cast Invoke result to correct type [OK]
Common Mistakes:
  • Ignoring cast from object to int
  • Thinking GetMethod("Parse") is invalid
  • Assuming typeof(int) is wrong
5. You want to load a plugin assembly at runtime and call its method Run without knowing the class name beforehand. Which reflection approach is best?
hard
A. Call Run method without loading assembly
B. Use typeof() with class name, then call Run directly
C. Use new operator with class name string
D. Use Assembly.Load, then find type with GetTypes(), then invoke Run method

Solution

  1. Step 1: Understand dynamic plugin loading

    When class name is unknown, you must load assembly dynamically and inspect types.
  2. Step 2: Use reflection to find and invoke method

    Assembly.Load loads the plugin. GetTypes() lists classes. Then you find the class with Run method and invoke it.
  3. Final Answer:

    Use Assembly.Load, then find type with GetTypes(), then invoke Run method -> Option D
  4. Quick Check:

    Dynamic loading needs Assembly.Load + reflection [OK]
Hint: Load assembly, find type, invoke method dynamically [OK]
Common Mistakes:
  • Using typeof() without knowing class name
  • Trying to instantiate class by string name directly
  • Calling method without loading assembly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard