Consider the following C# class with a property using get and set accessors. What will be printed when the program runs?
class Person { private string name; public string Name { get { return name; } set { name = value.ToUpper(); } } } class Program { static void Main() { Person p = new Person(); p.Name = "alice"; System.Console.WriteLine(p.Name); } }
Look at how the set accessor modifies the value before storing it.
The set accessor converts the input string to uppercase before storing it in the private field. So when we get the Name property, it returns the uppercase version.
Given this C# code, what will be the output?
class Counter { private int count; public int Count { get { return count; } set { if (value >= 0) count = value; } } } class Program { static void Main() { Counter c = new Counter(); c.Count = -5; System.Console.WriteLine(c.Count); } }
Check what happens when the set accessor receives a negative value.
The set accessor only assigns the value if it is zero or positive. Since -5 is negative, the private field remains at its default value 0.
Examine the following C# property. Why does it cause a runtime error?
class Sample { private int number; public int Number { get { return Number; } set { Number = value; } } }
Look at what the get and set accessors are returning and assigning.
The get accessor returns the property itself, not the private field, so it calls itself infinitely. The set accessor also assigns to the property, causing infinite recursion. This leads to a stack overflow error.
Choose the correct C# property syntax that allows reading the value publicly but only setting it privately within the class.
Remember the correct order and syntax for access modifiers on accessors.
Option C correctly places 'private' before 'set;' to restrict setting access. Other options have invalid syntax or misplaced modifiers.
Analyze this C# code using a property with get and set accessors that modify a dictionary. How many key-value pairs does the dictionary contain after execution?
class DataStore { public Dictionary<string, int> data = new(); public int this[string key] { get => data.ContainsKey(key) ? data[key] : -1; set { if (value >= 0) data[key] = value; else if (data.ContainsKey(key)) data.Remove(key); } } } class Program { static void Main() { DataStore store = new DataStore(); store["a"] = 10; store["b"] = 20; store["a"] = -5; store["c"] = 0; store["b"] = -1; System.Console.WriteLine(store.data.Count); } }
Track how the set accessor adds, updates, or removes keys based on the value.
Initially, keys 'a' and 'b' are added. Setting 'a' to -5 removes it. 'c' is added with 0. Setting 'b' to -1 removes it. Only 'c' remains, so count is 1.