what is the use of declaring
private Int64 _ID ;
public Int64 ID{get { return _ID; }set { _ID = value; } };
like this to declare a private variable
now normally in the coding we use ID directly which in turn access the _ID which is private. How this offers more security instead of directly declaring as
public int64 ID{get;set;}
Best of both:
public long ID {get;set;}
Wasn't that easier?
You should not expose fields as public
, but that doesn't mean you need to be verbose either.
You get the benefit
of encapsulation by get and set method to be call where you can put your custom logic
. The private _ID
is a place holder to hold the data for your property which is protected
by set method when some body writes to _id
, similarly you can put custom logic before giving the value by get
.
This is what msdn
explains about properties "Properties combine aspects of both fields and methods. To the user of an object, a property appears to be a field, accessing the property requires the same syntax. To the implementer of a class, a property is one or two code blocks, representing a get accessor and/or a set accessor. The code block for the get accessor is executed when the property is read; the code block for the set accessor is executed when the property is assigned a new value. A property without a set accessor is considered read-only. A property without a get accessor is considered write-only. A property that has both accessors is read-write". You can read more over here.
You should read about Properties
and Fields
. Properties provide better encapsulation and should be used instead of exposing public fields.
It bring security when you check the input or output before setting and getting values, look:
private int? _ID;
public int ID
{
get { return _ID ?? 0; }
set { _ID = value >= 0 ? value : 0; }
}
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