NOTE: This is not a question about auto-implemented properties. Auto-implemented properties are about properties without logic in the getters and setters while I stated in my code very clearly that there is some logic. This is not a duplicate of this question nither, since the question is really different, and so is the answer.
I see a lot of this:
private int _age;
public int Age
{
get
{
if(user.IsAuthorized)
{
return _age;
}
}
set
{
if(value >= 0 && value <= 120)
{
_age = value;
}
else
{
throw new ArgumentOutOfRangeException("Age","We do not accept immortals, nor unborn humans...");
}
}
}
But why do we need the backing field? Why no returning the Property itself?
public object Age
{
get
{
if(user.IsAuthorized)
{
return Age;
}
}
set
{
if(value >= 0 && value <= 120)
{
Age = value;
}
else
{
throw new ArgumentOutOfRangeException("Age","We do not accept immortals, nor unborn humans...");
}
}
}
Well, returning property itself leads to Stack Overflow exception:
public object Property
{
get
{
return Property;
}
set
{
Property = value;
}
}
Imagine
MyObject o = new MyObject();
// cause Stack Overflow exception
o.Property = null;
It easy to see why:
Property = null
calls set
Property = value;
which in turn calls set
Property = value;
... and so on.So if property stores some value the value should be stored in a field (you need a field), we can't use a property to store itself. If you want to shorten the code, put it like this (auto properties):
public object Property {
get; // let .Net create a backing field for you
set;
}
The property there is actually just two hidden methods: get_Property
and set_Property
. If you return Property
from the getter of Property
you are in fact causing an infinite recursive loop which will lead to a stack overflow exception: you are calling the method get_Property
from the method get_Property
, which in turn calls get_Property
and so forth.
EDIT: As clarified in the comments, the property is only the two methods and nothing more. There is nothing to hold data; the backing field is what actually contains the data. If you want to store Age
as data in the instance, something must hold that data which is why you need the backing field.
Auto-properties automatically create the backing field:
public object Property { get; set; }
In all other cases, the property is just two methods and all data storage is separate and you must handle it yourself.
Everytime you set a value to Property, the set-block will be called. So in your example it would be like:
Property = 10
-- Inside set: Property = Set
----- Called again set: Property = Set
----------- And so on and so o
n
But, you can do the following:
public int Property
{
get;
set;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With