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

Properties vs fields in C Sharp (C#) - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Properties vs Fields Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of accessing property vs field

What is the output of this C# code?

C Sharp (C#)
class Person {
    public string Name = "Alice";
    private int age = 30;
    public int Age {
        get { return age; }
        set { age = value; }
    }
}

var p = new Person();
Console.WriteLine(p.Name);
Console.WriteLine(p.Age);
Anull\n30
BAlice\n0
Cnull\n0
DAlice\n30
Attempts:
2 left
💡 Hint

Fields hold data directly. Properties can control access but here just return the field.

Predict Output
intermediate
2:00remaining
Effect of changing property setter

What is the output of this C# code?

C Sharp (C#)
class Counter {
    private int count = 0;
    public int Count {
        get { return count; }
        set { if (value > count) count = value; }
    }
}

var c = new Counter();
c.Count = 5;
c.Count = 3;
Console.WriteLine(c.Count);
A3
B5
C0
D8
Attempts:
2 left
💡 Hint

The setter only updates if the new value is greater than current.

🔧 Debug
advanced
2:00remaining
Why does this property cause a stack overflow?

What error does this code cause and why?

C Sharp (C#)
class Sample {
    private int value;
    public int Value {
        get { return value; }
        set { this.value = value; }
    }
}

var s = new Sample();
s.Value = 10;
Console.WriteLine(s.Value);
AStackOverflowException because property calls itself recursively
BNullReferenceException because value is null
CCompilation error due to missing semicolon
DOutput is 10
Attempts:
2 left
💡 Hint

The property getter and setter use the property name inside themselves.

🧠 Conceptual
advanced
2:00remaining
Difference between auto-property and field

Which statement correctly describes the difference between an auto-property and a field in C#?

AAn auto-property has hidden backing field and can have logic in get/set; a field is just data storage.
BA field can have get/set logic; an auto-property cannot.
CAn auto-property is slower because it uses reflection; a field is faster.
DA field can only be private; an auto-property can only be public.
Attempts:
2 left
💡 Hint

Think about what code the compiler generates for auto-properties.

Predict Output
expert
2:00remaining
Output of property with expression-bodied members

What is the output of this C# code?

C Sharp (C#)
class Rectangle {
    public int Width { get; set; }
    public int Height { get; set; }
    public int Area => Width * Height;
}

var r = new Rectangle { Width = 4, Height = 5 };
Console.WriteLine(r.Area);
ACompilation error
B9
C20
D0
Attempts:
2 left
💡 Hint

Expression-bodied properties calculate value on access.