Bird
0
0

How can you combine init-only setters with inheritance to allow derived classes to set base class properties only during initialization?

hard🚀 Application Q9 of 15
C Sharp (C#) - Properties and Encapsulation
How can you combine init-only setters with inheritance to allow derived classes to set base class properties only during initialization?
public class Vehicle {
    public string Make { get; init; }
}
public class Car : Vehicle {
    public string Model { get; init; }
}
AMake properties private to allow setting only in base class.
BAssign Make and Model properties anywhere in Car methods after creation.
COverride Make property with a set accessor in Car class.
DUse object initializers to set both Make and Model when creating Car instances.
Step-by-Step Solution
Solution:
  1. Step 1: Understand init-only setters in inheritance

    Init-only properties in base and derived classes can be set during object initialization.
  2. Step 2: Analyze options for setting properties

    Use object initializers to set both Make and Model when creating Car instances. correctly uses object initializers to set both properties at creation; A restricts access unnecessarily; B and C violate init-only rules.
  3. Final Answer:

    Use object initializers to set both Make and Model when creating Car instances. -> Option D
  4. Quick Check:

    Init-only in inheritance set via initializer = Use object initializers to set both Make and Model when creating Car instances. [OK]
Quick Trick: Set base and derived init-only properties in initializer [OK]
Common Mistakes:
MISTAKES
  • Trying to assign init-only properties after creation
  • Overriding init-only with set accessor
  • Making properties private unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes