using System; class Person { private int age; public int Age { get => age; set { if (value < 0 || value > 120) Console.WriteLine("Invalid age"); else age = value; } } } class Program { static void Main() { Person p = new Person(); p.Age = 25; Console.WriteLine(p.Age); p.Age = -5; Console.WriteLine(p.Age); } }
The setter only updates the private field age if the value is valid. When setting -5, it prints "Invalid age" but does not change age. So the last printed age remains 25.
using System; class Product { private decimal price; public decimal Price { get { return price; } set { if (value < 0) throw new ArgumentException("Price cannot be negative"); else Price = value; } } }
The setter calls Price = value; which calls the setter again, causing infinite recursion and a StackOverflowException at runtime.
Using a private field with lock in getter and setter ensures that only one thread accesses the field at a time, preventing inconsistent state.
using System; class Game { private int score; public int Score { get => score; set { if (value < 0) throw new ArgumentException("Score cannot be negative"); score = value; } } }
The condition if (score < 0) checks the current field value, not the new value value. So negative inputs are not caught.
using System; using System.Collections.Generic; class Registry { private Dictionary<string, int> data = new(); private int value; public int Value { get => value; set { if (value >= 0) { this.value = value; data[$"key{value}"] = value; } } } public int Count => data.Count; } class Program { static void Main() { Registry r = new Registry(); r.Value = 1; r.Value = 2; r.Value = -1; r.Value = 2; Console.WriteLine(r.Count); } }
The dictionary keys are "key1" and "key2" after valid assignments. The negative value is ignored. Assigning "key2" twice overwrites the same entry, so total count is 2.
