I'm creating a C# phone book application which takes input from a user (first name, last name, and phone number), stores it on a text file, and can display it on a Windows Form. Currently, when I start the program I get a StackOverflowException inside this method:
public string Phone
{
get { return Phone; }
set
{ // VS says that StackOverflowException happens here
if (value.Length == 10)
{
Phone = value;
}
else
{
Phone = "0000000000";
}
}
}
I believe that the exception happens when I try to read the phone number from the text file. Following code is from Read method:
foreach (var line in lines)
{
string[] entries = line.Split('`');
Contact newContact = new Contact();
newContact.FirstName = entries[0];
newContact.LastName = entries[1];
newContact.Phone = entries[2]; //I think exception happens here
contactList.Add(newContact);
However, when I put a breakpoint at that line and go into debug mode, when I hover over Phone
in the line Phone = value;
, VS exits debug mode after about 6 seconds. This is the output after I hover Phone
and VS exits debug mode:
ContactsList.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. The program '[5200] ContactsList.vshost.exe: Managed (v4.0.30319)' has exited with code -2147023895 (0x800703e9).
I've tried many solutions (restarting VS, cleaning and rebuilding solution, enabling/disabling different settings), but for the life of me I can't figure out the problem. Tried looking up exit code 0x800703e9
, still now idea what it is, all I know is that it has something to do with StackOverflowException. Any solutions to this problem?
Whenever you assign a value to the property Phone
its setter will get triggered, in the setter you have assigned the values to the same variable again so it again triggers the same and the process will continue. So your code will produce infinite assignments use a backup private property like the following:
private string _Phone;
public string Phone
{
get { return _Phone; }
set
{ // VS says that StackOverflowException happens here
if (value.Length == 10)
{
_Phone = value;
}
else
{
_Phone = "0000000000";
}
}
}
Now you are safe from such recursive assignments since you are using a backup property here, so while assigning values you are storing them in _Phone
and retrieving the value from the _Phone
through get
User contributions licensed under CC BY-SA 3.0