What is the output of this C# code?
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);
Fields hold data directly. Properties can control access but here just return the field.
The field Name is set to "Alice". The property Age returns the private field age which is 30. So output is "Alice" and "30".
What is the output of this C# code?
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);
The setter only updates if the new value is greater than current.
First Count is set to 5. Then setting to 3 is ignored because 3 < 5. So final value is 5.
What error does this code cause and why?
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);
The property getter and setter use the property name inside themselves.
The getter calls Value which calls the getter again endlessly. Same for setter. This causes a stack overflow.
Which statement correctly describes the difference between an auto-property and a field in C#?
Think about what code the compiler generates for auto-properties.
Auto-properties create a hidden field automatically and allow get/set accessors. Fields are just variables without accessors.
What is the output of this C# code?
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);
Expression-bodied properties calculate value on access.
The Area property returns Width * Height. With Width=4 and Height=5, Area is 20.