Shortened version of setting and getting properties
-
Hi, Is there any difference in the following with regards to security? private int _orderId; public int OrderId { get { return _orderId; } set { _orderId = value; } } ...and... public int OrderId { get; set; } When should we use the one and not the other? Regards
-
Hi, Is there any difference in the following with regards to security? private int _orderId; public int OrderId { get { return _orderId; } set { _orderId = value; } } ...and... public int OrderId { get; set; } When should we use the one and not the other? Regards
.NET Enthusiast wrote:
Is there any difference in the following with regards to security?
No. The only difference is compiler will generate the backing field for automated properties.
.NET Enthusiast wrote:
When should we use the one and not the other?
If you want more control over the getter and setter, you need to use the first one. For example, when
OrderId
is set, you need to fire an event. Something like,private int _orderId;
public int OrderId
{
get { return _orderId; }
set { _
orderId = value;
PropertyChanged(/* ... */);
}
}In all other cases, automated properties are just fine. :)
Best wishes, Navaneeth
-
Hi, Is there any difference in the following with regards to security? private int _orderId; public int OrderId { get { return _orderId; } set { _orderId = value; } } ...and... public int OrderId { get; set; } When should we use the one and not the other? Regards
In addition to the already correct answer you have, when using automatic properties you must have both a getter and setter. If you wish to have a read only property you have to mark the setter as private. If using your own backing field you only have to provide the getter.
Dave
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
Why are you using VB6? Do you hate yourself? (Christian Graus) -
.NET Enthusiast wrote:
Is there any difference in the following with regards to security?
No. The only difference is compiler will generate the backing field for automated properties.
.NET Enthusiast wrote:
When should we use the one and not the other?
If you want more control over the getter and setter, you need to use the first one. For example, when
OrderId
is set, you need to fire an event. Something like,private int _orderId;
public int OrderId
{
get { return _orderId; }
set { _
orderId = value;
PropertyChanged(/* ... */);
}
}In all other cases, automated properties are just fine. :)
Best wishes, Navaneeth
Thanks Navaneeth :)