Private variable access

what is ad usage

private Int64 _ID ; public Int64 ID{get { return _ID; }set { _ID = value; } }; 

to declare a private variable

Now, as a rule, in coding we use an ID, which, in turn, gets access to the _ID, which is private. How does this provide greater security instead of directly declaring how

 public int64 ID{get;set;} 
+7
source share
4 answers

You get the benefit encapsulation with the get and set method for the call, where you can put your custom logic . A private _ID is the owner of the data storage space for your property, which is the protected set method when any body writes to _ID , similarly you can put custom logic before giving a get value.

This is what msdn explains the properties. Properties combine aspects of both fields and methods. For the user of the object, the property looks like a field; accessing the property requires the same syntax. class, a property is one or two code blocks representing a get accessor and / or access set. The code block for get accessor is executed when the property is read, the code block for set access is executed when the property is assigned a new value. A property without a set accessory is considered read-only. A property without an access accessor is considered write-only. A property that has both accesses is read-write. You can read more here .

+3
source

The best of them:

 public long ID {get;set;} 

Isn't that easier?

You should not expose fields as public , but this does not mean that you also need to be detailed.

+4
source

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

+2
source

This provides security when you check input or output before setting and getting values, see:

 private int? _ID; public int ID { get { return _ID ?? 0; } set { _ID = value >= 0 ? value : 0; } } 
+2
source

All Articles