So i am currently learning about events and delegates and wanted to make some testing. I created a class called car. My idea was that everytime i change the value of its tires i want to invoke the event. This is all only for learning purposes. I get an StackoverflowException and i can not figure out why.
private static void Main(string[] args)
{
var Car = new Car { Tire_Value = 100 };
Car.OnTireChanged = Tirestatus;
Car.Tire_Value = 10;
}
public class Car
{
public event EventHandler OnTireChanged;
public int Tire_Value
{
get
{
return this.Tire_Value;
}
set
{
this.Tire_Value = value;
this.OnTireChanged?.Invoke(this, EventArgs.Empty);
}
}
}
private static void Tirestatus(object sender, EventArgs args)
{
var car = (Car)sender;
if (car.Tire_Value < 40) Console.WriteLine("Tire is damaged");
}
CodePudding user response:
When you are setting Tire_Value
to a value, your setter is executed, which attempts to call the setter on Tire_Value
again, resulting in an infinite loop, and the eventual stack overflow.
The solution to this problem are private backing fields. You declare a private variable of the same type as the public property, in which you store the value. When implementing your custom getter and setter, you use the private field.
This works:
private int _tireValue;
public int TireValue
{
get => _tireValue;
set
{
_tireValue = value;
OnTireChanged?.Invoke(this, EventArgs.Empty);
}
}
You can read another explanation on a different answer. As mentioned there, you can use an automatic property to avoid private backing fields.