Reputation:
In my base class, the one that the others inherit from, has these properties:
private int DEFAULT_DISPLAY_ORDER = 999999;
private DateTime DEFAULT_DT = new DateTime(1111,1,1);
public int? Id {
get
{
return Id.GetValueOrDefault(0);
}
set
{
if (DisplayOrder == null) DisplayOrder = DEFAULT_DISPLAY_ORDER;
Id = value;
}
}
public String Description { get; set; }
public int? DisplayOrder { get; set; }
But when I execute it, I get this error:
+ $exception {
Cannot evaluate expression because the current thread is in a stack
overflow state.}
System.Exception {System.StackOverflowException}
on line
if (DisplayOrder == null) DisplayOrder = DEFAULT_DISPLAY_ORDER;
What the heck is going on here?
Upvotes: 1
Views: 6223
Reputation: 2720
You're creating a infinite loop, because you are referring to Id property in get and set of the Id property :P. So in get, you are getting to get the getting ;). And in the set, you are setting to set the setting. Weird huh? :)
Upvotes: 1
Reputation: 6559
When you call Id, it calls Id again recursively over and over.
return Id.GetValueOrDefault(0);
Upvotes: 0
Reputation: 5832
Id = value;
This does. You are doing recursive assignment to property inside the same property.
Upvotes: 0
Reputation: 1502536
Look at this:
public int? Id {
get
{
return Id.GetValueOrDefault(0);
}
Here, accessing Id
requires that you first fetch... Id
. Bang.
Next:
set
{
if (DisplayOrder == null) DisplayOrder = DEFAULT_DISPLAY_ORDER;
Id = value;
}
Look at the second part. In order to set Id
, you have to... call the setter for Id
. Bang.
You need a field for this:
private int? id;
// Now use the field in the property bodies
public int? Id {
get
{
return id.GetValueOrDefault(0);
}
set
{
if (DisplayOrder == null) DisplayOrder = DEFAULT_DISPLAY_ORDER;
id = value;
}
}
Upvotes: 10
Reputation: 9565
ID = value
will set off a loop. You should have a private variable like _id
and use it in the setter and getter portions of the property.
Upvotes: 1
Reputation: 14002
You are calling Id from within itself - infinitely recursive... not good :)
public int? Id {
get
{
return Id.GetValueOrDefault(0); // This will keep calling the getter of Id. You need a backing field instead.
}
set
{
if (DisplayOrder == null) DisplayOrder = DEFAULT_DISPLAY_ORDER;
Id = value; // And here...
}
}
Upvotes: 3