I've been going through examples for properties compared to fields, and one thing I always see without explanation is the creation of a private field, and then a property. Why do we need _foo, and can't just run the code similar to what I have below, or maybe replace Foo = Foo with Foo = value?
I saw it created a stack overflow exception when I ran it, so I guess it's looking for a value to fill Foo or value with, but I would think that would be handled when I do def.Foo = 55.
Even if it is best practice to create the private field, I'd still like to get a better understanding of what's actually causing the overflow.
class ABC
{
private int _foo; //Why create this?
public int Foo
{
get { return Foo; }
set
{
Foo = Foo;//more logic would go here. }
}
}
}
class Program
{
static void Main(string[] args)
{
ABC def = new ABC();
def.Foo = 55;
Console.WriteLine($"The value of Foo is {def.Foo}.");
Console.ReadLine();
}
}