Challenge - 5 Problems
Init-only Setter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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);
Attempts:
2 left
💡 Hint
Init-only properties can be set during object initialization.
✗ Incorrect
The init-only setter allows setting the property only during object initialization. Here, Name is set to "Alice" when creating the object, so printing p.Name outputs "Alice".
❓ Predict Output
intermediate2: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);
Attempts:
2 left
💡 Hint
Init-only properties cannot be assigned outside initialization.
✗ Incorrect
The line 'car.Model = "Coupe";' is invalid because init-only properties can only be set during initialization. This causes a compilation error.
🔧 Debug
advanced2: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);
Attempts:
2 left
💡 Hint
Check when init-only properties can be assigned.
✗ Incorrect
Init-only properties can only be assigned during object initialization, not after. Here, 'b.Title = "C# Guide";' is outside initialization, causing a compile error.
🧠 Conceptual
advanced2: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}");
Attempts:
2 left
💡 Hint
Init-only setters work with inheritance and can be set during initialization.
✗ Incorrect
Both Species and Breed are init-only properties. They are set during object initialization, so the output is "Canine - Beagle".
📝 Syntax
expert2: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?
Attempts:
2 left
💡 Hint
Remember when init-only properties can be assigned.
✗ Incorrect
Option A tries to assign to the init-only property Name after initialization, causing a compilation error. Options A, C, and D are valid uses.