0
0
C Sharp (C#)programming~20 mins

Object instantiation with new in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Object Instantiation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code?
Consider the following C# code snippet. What will be printed to the console?
C Sharp (C#)
class Person {
    public string Name;
    public Person(string name) {
        Name = name;
    }
}

Person p = new Person("Alice");
Console.WriteLine(p.Name);
ACompilation error
Bnull
CPerson
DAlice
Attempts:
2 left
💡 Hint
Look at how the constructor sets the Name property.
Predict Output
intermediate
2:00remaining
What happens when you instantiate a class without a constructor?
What will be the output of this code?
C Sharp (C#)
class Box {
    public int Width = 5;
}

Box b = new Box();
Console.WriteLine(b.Width);
A0
BNullReferenceException
C5
DCompilation error
Attempts:
2 left
💡 Hint
Fields with initial values keep those values even without a constructor.
Predict Output
advanced
2:00remaining
What is the output of this code with multiple constructors?
What will this program print?
C Sharp (C#)
class Car {
    public string Model;
    public int Year;

    public Car() {
        Model = "Unknown";
        Year = 0;
    }

    public Car(string model, int year) {
        Model = model;
        Year = year;
    }
}

Car car = new Car("Tesla", 2023);
Console.WriteLine($"{car.Model} {car.Year}");
AUnknown 0
BTesla 2023
CTesla 0
DCompilation error
Attempts:
2 left
💡 Hint
Which constructor is called depends on the parameters passed with new.
Predict Output
advanced
2:00remaining
What error does this code raise?
What happens when you run this code?
C Sharp (C#)
class Animal {
    public string Name;
}

Animal a = new Animal();
Console.WriteLine(a.Name.Length);
ANullReferenceException
B0
CCompilation error
DEmpty string printed
Attempts:
2 left
💡 Hint
Name is not initialized, so it is null by default.
🧠 Conceptual
expert
2:00remaining
How many objects are created here?
How many objects are created in memory after running this code?
C Sharp (C#)
class Node {
    public Node Next;
}

Node first = new Node();
first.Next = new Node();
A2
B1
C0
D3
Attempts:
2 left
💡 Hint
Each 'new' keyword creates one object.