Bird
0
0

Given this record declaration:

hard🚀 Application Q15 of 15
C Sharp (C#) - Properties and Encapsulation
Given this record declaration:
public record Book {
    public string Title { get; init; }
    public string Author { get; init; }
}

var book1 = new Book { Title = "C# Guide", Author = "Jane" };
var book2 = book1 with { Author = "John" };

Console.WriteLine(book2.Title + ", " + book2.Author);

What is the output?
AC# Guide, John
BC# Guide, Jane
CCompile-time error due to init-only setter
DRuntime exception
Step-by-Step Solution
Solution:
  1. Step 1: Understand 'with' expression on records

    The 'with' expression creates a copy of book1 but allows changing init-only properties during creation of the new object.
  2. Step 2: Analyze the output

    book2 copies Title as "C# Guide" and sets Author to "John". Printing shows "C# Guide, John".
  3. Final Answer:

    C# Guide, John -> Option A
  4. Quick Check:

    'with' allows changing init-only during copy [OK]
Quick Trick: 'with' can set init-only properties on new record copies [OK]
Common Mistakes:
MISTAKES
  • Thinking 'with' cannot change init-only properties
  • Expecting compile error on 'with' usage
  • Confusing init-only with immutable fields

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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