Asked
Active
Viewed 56 times
-4
-
1Because you are setting the property again. Recursively. You need a backing *field* if you want to use this form of properties – pinkfloydx33 Jul 18 '20 at 17:24
2 Answers
1
you get a stack overflow because your setter recursively calls your setter recursively calls your setter recursively calls your setter......
you need to have a backing field for this, like so:
public class Student {
private int _sid;
public int Sid
{
set
{
if (value <= 0) Console.WriteLine("Id must be positive.");
else _sid = value;
}
get { return _sid; }
}

Franz Gleichmann
- 3,420
- 4
- 20
- 30
1
Your properties are recursively calling themselves. Take your Sid
property
public int Sid
{
set
{
if (Sid <= 0) Console.WriteLine("Id must be positive."); // here, also validation wrong--use value
else Sid = value; // here
}
get { return Sid; } //here
}
Where I've marked, the getter and setter are invoking Sid
again. This causes them to be called recursively until the stack overflows. If you want to perform validation in a property, you'll need to use explicit backing fields:
private int _sid;
public int Sid
{
set
{
if (value <= 0) Console.WriteLine("Id must be positive.");
else _sid = value;
}
get { return _sid; }
}
You should also consider taking action in your setter when validation fails. Simply outputting to the console is unexpected. The user gets no indication (via code) that something is wrong. Consider throwing an exception instead.
private int _sid;
public int Sid
{
set
{
if (value <= 0)
throw new InvalidOperationException("Id must be positive.");
_sid = value;
}
get => _sid;
}

pinkfloydx33
- 11,863
- 3
- 46
- 63