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

Creating instances dynamically in C Sharp (C#) - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Dynamic Instance Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of dynamic instance creation with Activator.CreateInstance
What is the output of this C# code that creates an instance dynamically?
C Sharp (C#)
using System;

class Person {
    public string Name { get; set; } = "Unknown";
    public override string ToString() => $"Person: {Name}";
}

class Program {
    static void Main() {
        Type t = typeof(Person);
        var obj = Activator.CreateInstance(t);
        Console.WriteLine(obj.ToString());
    }
}
ASystem.Object
BPerson: Unknown
CNullReferenceException
DPerson:
Attempts:
2 left
💡 Hint
Activator.CreateInstance creates an object using the default constructor.
❓ Predict Output
intermediate
2:00remaining
Output when creating instance with parameterized constructor dynamically
What will this C# code print when creating an instance dynamically with parameters?
C Sharp (C#)
using System;
using System.Reflection;

class Car {
    public string Model { get; }
    public Car(string model) {
        Model = model;
    }
    public override string ToString() => $"Car model: {Model}";
}

class Program {
    static void Main() {
        Type t = typeof(Car);
        object obj = Activator.CreateInstance(t, new object[] { "Tesla" });
        Console.WriteLine(obj.ToString());
    }
}
ASystem.Object
BCar model:
CMissingMethodException
DCar model: Tesla
Attempts:
2 left
💡 Hint
Activator.CreateInstance can pass constructor arguments as an object array.
🔧 Debug
advanced
2:00remaining
Identify the error when creating instance dynamically without default constructor
What error does this code produce when trying to create an instance dynamically?
C Sharp (C#)
using System;

class Book {
    public string Title { get; }
    public Book(string title) {
        Title = title;
    }
}

class Program {
    static void Main() {
        Type t = typeof(Book);
        var obj = Activator.CreateInstance(t);
        Console.WriteLine(obj);
    }
}
AMissingMethodException
BNullReferenceException
CInvalidCastException
DNo error, prints Book object
Attempts:
2 left
💡 Hint
Activator.CreateInstance without parameters requires a default constructor.
📝 Syntax
advanced
2:00remaining
Which code snippet correctly creates an instance dynamically using reflection?
Choose the code snippet that correctly creates an instance of class Animal dynamically with a default constructor.
Avar obj = Activator.CreateInstance(typeof(Animal));
Bvar obj = typeof(Animal).CreateInstance();
Cvar obj = Activator.CreateInstance<Animal>();
Dvar obj = new Activator(typeof(Animal));
Attempts:
2 left
💡 Hint
Activator.CreateInstance(Type) is the correct method to create an instance dynamically.
🚀 Application
expert
2:00remaining
How many instances are created dynamically in this code?
Given this code, how many objects are created dynamically using Activator.CreateInstance?
C Sharp (C#)
using System;
using System.Collections.Generic;

class Shape {
    public string Name { get; set; }
    public Shape() { Name = "Shape"; }
}

class Program {
    static void Main() {
        List<object> shapes = new List<object>();
        Type shapeType = typeof(Shape);
        for (int i = 0; i < 3; i++) {
            var shape = Activator.CreateInstance(shapeType);
            shapes.Add(shape);
        }
        Console.WriteLine(shapes.Count);
    }
}
A0
B1
C3
D4
Attempts:
2 left
💡 Hint
Activator.CreateInstance is called inside a loop 3 times.

Practice

(1/5)
1. What does Activator.CreateInstance(typeof(MyClass)) do in C#?
easy
A. Creates a new instance of the class MyClass at runtime.
B. Deletes an existing instance of MyClass.
C. Checks if MyClass has a default constructor.
D. Converts MyClass to a string representation.

Solution

  1. Step 1: Understand Activator.CreateInstance usage

    Activator.CreateInstance is used to create objects dynamically when the type is known only at runtime.
  2. Step 2: Analyze the given code

    The code Activator.CreateInstance(typeof(MyClass)) creates a new instance of MyClass using its default constructor.
  3. Final Answer:

    Creates a new instance of the class MyClass at runtime. -> Option A
  4. Quick Check:

    Activator.CreateInstance creates objects dynamically [OK]
Hint: Activator.CreateInstance makes objects when type is known at runtime [OK]
Common Mistakes:
  • Thinking it deletes or modifies existing objects
  • Confusing it with type checking or conversion
  • Assuming it calls any constructor without matching parameters
2. Which of the following is the correct syntax to create an instance of Person dynamically using Activator.CreateInstance?
easy
A. var obj = Activator.CreateInstance(typeof(Person));
B. var obj = new Activator.CreateInstance(typeof(Person));
C. var obj = Activator.CreateInstance<Person>(typeof(Person));
D. var obj = Person.CreateInstance();

Solution

  1. Step 1: Recall correct Activator.CreateInstance syntax

    The method Activator.CreateInstance takes a Type object as parameter, e.g., typeof(Person).
  2. Step 2: Evaluate each option

    var obj = Activator.CreateInstance<Person>(typeof(Person)); uses generic syntax incorrectly by passing a Type argument. var obj = new Activator.CreateInstance(typeof(Person)); tries to use new with a method call, which is wrong. var obj = Activator.CreateInstance(typeof(Person)); correctly calls Activator.CreateInstance(typeof(Person)). var obj = Person.CreateInstance(); calls a non-existent method.
  3. Final Answer:

    var obj = Activator.CreateInstance(typeof(Person)); -> Option A
  4. Quick Check:

    Use typeof(Type) inside Activator.CreateInstance [OK]
Hint: Use typeof(Type) inside Activator.CreateInstance() [OK]
Common Mistakes:
  • Using new keyword with Activator.CreateInstance
  • Trying to call generic version incorrectly
  • Calling non-existent CreateInstance on the class
3. What will be the output of this code?
class Animal { public string Name; public Animal() { Name = "Dog"; } }
var obj = Activator.CreateInstance(typeof(Animal));
Console.WriteLine(((Animal)obj).Name);
medium
A. null
B. Compilation error
C. Animal
D. Dog

Solution

  1. Step 1: Understand the class and constructor

    The class Animal has a default constructor that sets Name to "Dog".
  2. Step 2: Analyze Activator.CreateInstance and output

    Activator.CreateInstance(typeof(Animal)) creates a new Animal object, calling the default constructor. So Name is "Dog". The Console.WriteLine prints this value.
  3. Final Answer:

    Dog -> Option D
  4. Quick Check:

    Default constructor sets Name to Dog [OK]
Hint: Activator calls default constructor, so fields are initialized [OK]
Common Mistakes:
  • Assuming Name is null because of dynamic creation
  • Thinking output is class name string
  • Expecting compile or runtime error
4. Identify the error in this code snippet:
class Car { public int Speed; public Car(int speed) { Speed = speed; } }
var obj = Activator.CreateInstance(typeof(Car));
medium
A. No error, instance created successfully.
B. Missing parameterless constructor causes runtime exception.
C. Syntax error in Activator.CreateInstance call.
D. Cannot create instance of class with fields.

Solution

  1. Step 1: Check constructors in Car class

    The class Car has only a constructor with an int parameter. No default (parameterless) constructor exists.
  2. Step 2: Understand Activator.CreateInstance behavior

    Activator.CreateInstance(typeof(Car)) tries to call the default constructor. Since none exists, it throws a runtime exception.
  3. Final Answer:

    Missing parameterless constructor causes runtime exception. -> Option B
  4. Quick Check:

    Activator needs parameterless constructor unless parameters passed [OK]
Hint: Activator.CreateInstance needs parameterless constructor unless parameters given [OK]
Common Mistakes:
  • Assuming it creates instance without matching constructor
  • Thinking it's a syntax error
  • Believing fields prevent instance creation
5. You want to create an instance of a class dynamically and pass constructor parameters. Which is the correct way to do this?
class Book { public string Title; public Book(string title) { Title = title; } }
hard
A. var obj = new Book("C# Guide");
B. var obj = Activator.CreateInstance<Book>(typeof(Book));
C. var obj = Activator.CreateInstance(typeof(Book), "C# Guide");
D. var obj = Activator.CreateInstance(typeof(Book)); obj.Title = "C# Guide";

Solution

  1. Step 1: Understand how to pass parameters with Activator.CreateInstance

    To call a constructor with parameters dynamically, pass them as additional arguments after the type.
  2. Step 2: Evaluate options

    var obj = Activator.CreateInstance<Book>(typeof(Book)); uses invalid generic syntax by passing a Type argument. var obj = new Book("C# Guide"); uses normal instantiation, not dynamic. var obj = Activator.CreateInstance(typeof(Book), "C# Guide"); correctly passes the string parameter to the constructor. var obj = Activator.CreateInstance(typeof(Book)); obj.Title = "C# Guide"; creates default instance (which fails) and sets property manually, but no default constructor exists.
  3. Final Answer:

    var obj = Activator.CreateInstance(typeof(Book), "C# Guide"); -> Option C
  4. Quick Check:

    Pass constructor args after type in Activator.CreateInstance [OK]
Hint: Pass constructor arguments after type in Activator.CreateInstance [OK]
Common Mistakes:
  • Using generic syntax incorrectly
  • Trying to set properties after creation without default constructor
  • Confusing normal new with dynamic creation
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