Reputation: 925
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;}
Upvotes: 7
Views: 159
Reputation: 148120
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.
Upvotes: 3
Reputation: 13582
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; }
}
Upvotes: 2
Reputation: 1038830
You should read about Properties
and Fields
. Properties provide better encapsulation and should be used instead of exposing public fields.
Upvotes: 2
Reputation: 1062820
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.
Upvotes: 4