A StackOverflowException
is thrown in my program and I don't understand why.
Can someone please explain what is happening?
This screenshot shows where exactly the exception is being thrown: Exception
class Program
{
static void Main(string[] args)
{
var t = new WhiteWine();
t.Name = "Tom";
t.year = 1414;
string f = t.Prepare;
}
}
class WhiteWine : Wine
{
public override string Prepare
{
get
{
return $"Well, {this.Name} is a cold wine, therefor it served cold. \n All you need to di is take it out from the refrigerator, pour it into a glass and serve.";
}
}
public override string Name
{
get
{
return $"{this.Name} ({this.year})";
}
}
}
public class Wine : Drink
{
public int year { get; set; }
}
public class Drink : Idrink
{
public virtual string Name { get; set; }
public virtual string Prepare { get; }
}
The WhiteWine.Name
get accessor produces infinite recursion, because you use this.Name
to calculate the value of this.Name
.
public override string Name
{
get
{
return $"{base.Name} ({this.year})";
}
}
This should fix the issue.