selvaraj
selvaraj

Reputation: 899

main usage of properties(get,set)

Hi all we can assign a value or return a value many other way.. so sometimes we are doing by properties(get,set).. can any one tell me main use of properties..

thanks saj

Upvotes: 0

Views: 243

Answers (4)

Huzi--- Javiator
Huzi--- Javiator

Reputation: 3837

I would just say that using getters and setters on private fields, give you more control over those fields. You may want to allow only authorized entities to access that variables.. so you can put a check in the getField method. You may want to allow, only to read values and not update them , then you can have only getters and no setters. so basically with methods exposing the private fields , you have more control over them.

Upvotes: 0

Oded
Oded

Reputation: 498904

Properties encapsulate internal logic. They are the public interface and allow you to check values, apply rules and enable to change internal implementation.

This is in contrast to exposing internals directly.

For example:

public int myField; // exposes implementation - BAD BAD BAD

Is better implemented:

private int myField;
public int MyField
{
   get {return myField;}
   set {myField = value;}
}

You can now change the internal myField and not affect other code outside the class. You can add logic to the setter, to the getter and more.

If you don't have any logic associated with member access, you can use automatic properties:

public int MyField {get; set;}

The compiler will generate a backing field automatically.

Upvotes: 3

Musa Hafalir
Musa Hafalir

Reputation: 1770

Beside the advantages of encapsulation, we prefer using properties with get and set accessors among many other ways, because they provide a clear and practical syntax.

The syntax:

public int Field{ get; set; }

is more clear than this:

private int field;
public int GetField(){
     return field;
}
public void SetField(int field){
     this.field = field;
}

Upvotes: 0

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

Properties provides an abstraction for getting and setting state. I.e. they allow you to define what getting and setting means in the actual context. A common example of how this is used on setters is to notify subscribers when state change. This cannot be done if you expose public fields.

Upvotes: 5

Related Questions