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

Init-only setters in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Init-only Setter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of init-only property assignment
What will be the output of this C# code snippet using init-only setters?
C Sharp (C#)
public class Person {
    public string Name { get; init; }
}

var p = new Person { Name = "Alice" };
Console.WriteLine(p.Name);
AAlice
Bnull
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Init-only properties can be set during object initialization.
Predict Output
intermediate
2:00remaining
Error when setting init-only property after initialization
What happens if you try to set an init-only property after the object is created?
C Sharp (C#)
public class Car {
    public string Model { get; init; }
}

var car = new Car { Model = "Sedan" };
car.Model = "Coupe";
Console.WriteLine(car.Model);
AOutputs "Sedan"
BCompilation error
COutputs "Coupe"
DRuntime exception
Attempts:
2 left
💡 Hint
Init-only properties cannot be assigned outside initialization.
🔧 Debug
advanced
2:00remaining
Why does this init-only setter code fail to compile?
Identify the reason for the compilation error in this code using init-only setters.
C Sharp (C#)
public class Book {
    public string Title { get; init; }
}

var b = new Book();
b.Title = "C# Guide";
Console.WriteLine(b.Title);
ATitle property must be readonly to use init-only
BProperty Title is missing a setter
CInit-only property Title cannot be assigned outside object initialization
DMissing semicolon after object creation
Attempts:
2 left
💡 Hint
Check when init-only properties can be assigned.
🧠 Conceptual
advanced
2:00remaining
Understanding init-only setters with inheritance
Given these classes, what is the output of the program?
C Sharp (C#)
public class Animal {
    public string Species { get; init; }
}

public class Dog : Animal {
    public string Breed { get; init; }
}

var dog = new Dog { Species = "Canine", Breed = "Beagle" };
Console.WriteLine($"{dog.Species} - {dog.Breed}");
ACanine - null
BCompilation error due to init-only in base class
CRuntime exception
DCanine - Beagle
Attempts:
2 left
💡 Hint
Init-only setters work with inheritance and can be set during initialization.
📝 Syntax
expert
2:00remaining
Which option causes a compilation error with init-only setters?
Which of the following code snippets will NOT compile due to incorrect use of init-only setters?
Avar p = new Person { Name = "John" }; p.Name = "Jane";
Bvar p = new Person { Name = "John" }; Console.WriteLine(p.Name);
CPerson p = new() { Name = "John" };
Dvar p = new Person(); var q = p with { Name = "Jane" };
Attempts:
2 left
💡 Hint
Remember when init-only properties can be assigned.