Errors & Exceptions in C#
-
How to solve "System.StackOverflowException" I am getting this, when I try to set a value to memeber variable. namespace StackOverFLow { /// /// Summary description for Class1. /// class StFlow { /// /// The main entry point for the application. /// [STAThread] static void Main(string[] args) { StFlow STF = new StFlow(); STF.Name = "CodeProject"; string str = STF.Name; } public string Name { get { return Name; } set { Name = value; } } } } Thanks, Candy
-
How to solve "System.StackOverflowException" I am getting this, when I try to set a value to memeber variable. namespace StackOverFLow { /// /// Summary description for Class1. /// class StFlow { /// /// The main entry point for the application. /// [STAThread] static void Main(string[] args) { StFlow STF = new StFlow(); STF.Name = "CodeProject"; string str = STF.Name; } public string Name { get { return Name; } set { Name = value; } } } } Thanks, Candy
The problem is caused because your property is trying to get/set itself. You need a private field to store the value, and the property gets/sets that.
private string name;
public string Name {
get {
return name;
}
set {
name = value;
}
}Notice the different in case between
name
andName
. C# is case sensitive :) HTH, James Sonork ID: 100.11138 - Hasaki "Smile your little smile, take some tea with me awhile. And every day we'll turn another page. Behind our glass we'll sit and look at our ever-open book, One brown mouse sitting in a cage." "One Brown Mouse" from Heavy Horses, Jethro Tull 1978 -
How to solve "System.StackOverflowException" I am getting this, when I try to set a value to memeber variable. namespace StackOverFLow { /// /// Summary description for Class1. /// class StFlow { /// /// The main entry point for the application. /// [STAThread] static void Main(string[] args) { StFlow STF = new StFlow(); STF.Name = "CodeProject"; string str = STF.Name; } public string Name { get { return Name; } set { Name = value; } } } } Thanks, Candy
Every time you access Name within your getter or setter code, you recursively invoking it. It stops only when this call sequence exhaust the call stack. You can check it tracing execution in debugger. There are to possible ways to correct this. First is to just create the field: public string Name; // all problems gone the second one is to back up your property with the private field and use in getter and setter code: private string name; // lowercase n public string Name { get { return name; } // you are noo more recursively accessing getter here set { name = value; } // same for setter } Cheers, elk.