Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private variable accessing

Tags:

c#

private

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;}
like image 336
Raghurocks Avatar asked Dec 19 '12 07:12

Raghurocks


4 Answers

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.

like image 143
Marc Gravell Avatar answered Oct 15 '22 13:10

Marc Gravell


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.

like image 30
Adil Avatar answered Oct 15 '22 13:10

Adil


You should read about Properties and Fields. Properties provide better encapsulation and should be used instead of exposing public fields.

like image 35
Darin Dimitrov Avatar answered Oct 15 '22 11:10

Darin Dimitrov


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; } 
}
like image 33
Mahdi Tahsildari Avatar answered Oct 15 '22 12:10

Mahdi Tahsildari