Click to See Complete Forum and Search --> : System.StackOverflowException errors?


warnk
April 13th, 2009, 08:13 AM
I get some "System.StackOverflowException was unhandled" by running the following C# code, I don't understand why.

class Test
{
static void Main(string[] args)
{
Customer cust = new Customer();
cust.ID = 1;
cust.Name = "Parrot";
Console.WriteLine("ID: {0}, Name: {1}", cust.ID, cust.Name);
}
}

class Customer
{
public int ID { get; set; }

public string Name
{
get { return this.Name; }
set { this.Name = value.ToUpper(); }
}
}

JonnyPoet
April 13th, 2009, 11:18 AM
class Customer
{
public int ID { get; set; }

public string Name
{
get { return this.Name; }
set { this.Name = value.ToUpper(); }
}
}
The red (bold Italic) ones create an infinite loop. If you try to read the Nameproperty it wants to read the this.Name which again is an attempt to read the name property. You need to do

class Customer
{
private string _name;

public int ID { get; set; }

public string Name
{
get { return _name; }
set { _name = value.ToUpper(); }
}
}

Uppercase, lowercase is very necessary in C# !! ;) :D :wave:

warnk
April 13th, 2009, 01:10 PM
Thanks! :)