Bird
0
0

Examine this code snippet:

medium📝 Debug Q6 of 15
C Sharp (C#) - Properties and Encapsulation
Examine this code snippet:
public class Article {
    public string Title { get; init; }
}

var article = new Article();
article.Title = "C# Basics";

What is the issue here?
ACannot assign to init-only property outside object initializer
BProperty Title is missing a setter
CClass Article must be declared as a record to use init-only
DNo issue; code compiles and runs fine
Step-by-Step Solution
Solution:
  1. Step 1: Understand init-only property restrictions

    Properties with init can only be assigned during object initialization, such as in an object initializer or constructor.
  2. Step 2: Analyze the code

    The code creates an object with new Article() without initializing Title. Then it tries to assign Title after creation, which is not allowed.
  3. Step 3: Identify the error

    This results in a compilation error because the assignment is outside the initialization phase.
  4. Final Answer:

    Cannot assign to init-only property outside object initializer -> Option A
  5. Quick Check:

    Init-only properties disallow post-construction assignment [OK]
Quick Trick: Init-only properties only settable during initialization [OK]
Common Mistakes:
MISTAKES
  • Assuming init-only properties can be set anytime
  • Confusing init-only with readonly fields
  • Believing records are required for init-only setters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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