Why does Property Set throw StackOverflow exception?
It's because you're recursively calling the property - in the set
you are setting the property again, which continues ad infinitum until you blow the stack.
You need a private backing field to hold the value, e.g.
private string firstName;
public string FirstName
{
get
{
return this.firstName;
}
set
{
this.firstName = value;
}
}
Alternatively, if you're using C# 3.0, you could use an auto-property, which creates a hidden backing field for you, e.g.
public string FirstName { get; set; }
StackOverFlowException when setting property
The problem is you re-assigning within the same Property
which causes recursion:
public string Name
{
get { return Name; }
set
{
if (Name.CompareTo("Admin") == 0 || Name.CompareTo("Admin") == -1) //Just trying out comparison with the input.
{
Console.WriteLine("Invalid Name."); //To see if an invalid input that is not "Admin" fails.
}
else
{
Name = value; //StackOverFlow here
Console.WriteLine("Done.");
}
}
}
If you are validating it, you might wanna try a different approach.
Solution #1 (Using separate variable for Name
property)
private string name = "";
public string Name
{
get { return name; }
set
{
if (value != null) //Check for null before validation (or it's up to you how to handle NULL value)
{
if (value.CompareTo("Admin") == 0 || value.CompareTo("Admin") == -1) //Just trying out comparison with the input.
{
Console.WriteLine("Invalid Name."); //To see if an invalid input that is not "Admin" fails.
}
else
{
name = value;
Console.WriteLine("Done.");
}
}
}
}
Solution #2 (Making set
private and using separate setter
method.
public string Name
{
get;
private set; //Making this private means you can still
//access this setter within the class via `this.Name =` (so be careful)
}
/// <summary>
/// Defined a public setter which can be invoked outside
/// </summary>
/// <param name="value"></param>
public void SetName(string value)
{
if (value != null) //Check for null before validation (or it's up to you how to handle NULL value)
{
if (value.CompareTo("Admin") == 0 || value.CompareTo("Admin") == -1) //Just trying out comparison with the input.
{
Console.WriteLine("Invalid Name."); //To see if an invalid input that is not "Admin" fails.
}
else
{
Name = value;
Console.WriteLine("Done.");
}
}
}
public Workers(string Name)
{
this.SetName(Name); //be careful making this.Name = Name or else no validation
}
public Workers()
{
this.SetName(null); //be careful with this.Name = null or else no validation
}
The disadvantage of the second approach is that inside the class Workers
you should be careful when setting this.Name
because it still accessible inside Workers
even when set to private
.
StackOverflow Exception from get and set
public DateTime time
{
get { return this.time; }
set
{
this.time = value;
}
}
you aren't using backing fields, but setting the property itself from within the property setter.
You can fix this by using 1) an auto property
public DateTime Time { get; set; }
or 2) a backing field
private DateTime _time;
public Datetime Time
{
get { return _time; }
set { _time = value; }
}
they both equate to the same code.
For an explanation, when you get time
in your code:
get { return this.time; }
it has to retrieve the value of time
to return. It does that by calling the get
on time
, which has to get retrieve the value of time
, etc.
Why does this code throw StackOverFlow Exception?
That's because you call your property in your getter.
You can do two things: add a field/member to you class:
class Test
{
private string company;
public string Company
{
get
{
return company;
}
set
{
company = value;
}
}
}
Or change it to
public string Company{get; set;}
Stack Overflow exception while setting static property C#
set
{
stringToSet = value;
}
You got infinite recursion in your setter (and getter for that matter) since it calls itself, hence StackOverflow.
If you don't need to modify the underlying field directly, use an auto-property instead:
static string stringToSet {get; set;}
StackOverflowException in property setter
Your Metres
property has the same name as the backing field (variable), and is being recursively called. You may have been confused by automatic properties versus declaring the 'backing' field yourself.
You can implement like this:
class Distance
{
private double _meters;
public double Meters
{
get
{
return _meters;
}
set
{
_metres = value;
}
}
.....
Or like this:
class Distance
{
public double Metres{ get; set; }
....
Ref: Auto-Implemented Properties
Error: Exception of type 'System.StackOverflowException' was thrown in get property
You don't have a field to store the actual variable of that Property and by accessing LastName
you call yourself and hence the StackOverflowException
. The solution is to introduce a field and use the property to access it. Like so:
private string _lastName;
public string LastName
{
get => _lastName;
set
{
_lastName= value.TrimAndReduce();
}
}
Exception of type 'System.StackOverflowException' was thrown
When setting the price property, you invoke the setter, which invokes the setter which invokes the setter, etc..
Solution:
public int _price;
public int price
{
get
{
return no * 5;
}
set
{
_price = value;
}
}
How Stack overflow exception occurs when property sets value to Itself
When you make the getter's code {return Name;}
, you are recursing. How? When some code wants to get the value of Name
, your getter method just tells it, "Why don't you try asking me again?" See a problem? When you try getting a value, it'll tell you that you need to ask itself again. And again. And again!
Every time the property is accessed and the getter is called, a new entry is added to the stack. Since this code will only tell other code to keep trying over and over, the stack infinitely become more occupied! (Every time you call a method, like your getter, an entry is added to the stack)
Also, your updated question asks why the setter would cause a stack overflow. It's pretty much the same reason as before; when Name
's setter is called, it calls itself. Simple quote to explain? Name
says in response to your code, "If you want to set my value, try setting my value again?"
Where does it do that? In Name = value;
. You would try setting the value, but your method would tell it to set itself again. And again. And again.
How can we fix that? As the other answerer showed, you can create another variable that will store the actual content. For example, Name
will contain the getters and setters to successfully manipulate data. It won't store it in itself though, to avoid infinite recursion. It'll store it in another variable, like _Name
.
Related Topics
All Possible Array Initialization Syntaxes
Parse String to Datetime in C#
Should 'Using' Directives Be Inside or Outside the Namespace
Nesting Await in Parallel.Foreach
How to Create a Dropdownlist from an Enum in ASP.NET MVC
Performance Differences Between Debug and Release Builds
Creating a Byte Array from a Stream
How to Copy the Contents of One Stream to Another
Why Is Floating Point Arithmetic in C# Imprecise
How Would You Count Occurrences of a String (Actually a Char) Within a String
One Dbcontext Per Web Request... Why
How to Get All Child Controls of a Windows Forms Form of a Specific Type (Button/Textbox)
Convert Webpage to Image from Asp.Net
Reach Control from Another Page. Asp.Net
Entity Framework Code First - Two Foreign Keys from Same Table