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

Read-only and write-only properties in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Property Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a read-only property
What is the output of this C# code snippet?
C Sharp (C#)
class Person {
    private string name = "Alice";
    public string Name {
        get { return name; }
    }
}

var p = new Person();
Console.WriteLine(p.Name);
AAlice
Bnull
CCompilation error
DEmpty string
Attempts:
2 left
💡 Hint
Look at the get accessor and the initial value of the private field.
Predict Output
intermediate
2:00remaining
Effect of write-only property
What happens when you try to read a write-only property in this code?
C Sharp (C#)
class Secret {
    private string code;
    public string Code {
        set { code = value; }
    }
}

var s = new Secret();
s.Code = "1234";
Console.WriteLine(s.Code);
ACompilation error
Bnull
CRuntime exception
D1234
Attempts:
2 left
💡 Hint
Check if the property has a get accessor.
🧠 Conceptual
advanced
2:00remaining
Understanding read-only auto-properties
Which statement about this code is true?
C Sharp (C#)
class Data {
    public int Value { get; } = 10;
}

var d = new Data();
d.Value = 20;
ARuntime exception when assigning 20
BValue is updated to 20 successfully
CCompilation error because Value has no set accessor
DValue remains 10 but no error
Attempts:
2 left
💡 Hint
Check if the property allows assignment outside the constructor.
Predict Output
advanced
2:00remaining
Behavior of write-only property with backing field
What is the output of this code?
C Sharp (C#)
class Box {
    private int size = 5;
    public int Size {
        set { size = value; }
    }
    public int GetSize() => size;
}

var b = new Box();
b.Size = 10;
Console.WriteLine(b.GetSize());
A5
B10
CCompilation error
D0
Attempts:
2 left
💡 Hint
The property sets the private field, and GetSize returns it.
🔧 Debug
expert
3:00remaining
Why does this read-only property cause a compilation error?
Identify the cause of the compilation error in this code snippet.
C Sharp (C#)
class Counter {
    private int count;
    public int Count {
        get { return count; }
    }

    public void Increment() {
        Count++;
    }
}
AThe Count property causes a stack overflow due to recursive get/set
BThe Count property cannot be incremented because the set accessor is private
CThe Increment method syntax is invalid
DThe Count property is missing a set accessor
Attempts:
2 left
💡 Hint
Consider what happens when Count++ is executed with this property implementation.