Whats the use of get and set in c# when we can add a property value like this

object.property="value"

Whats the use of get and set in c# when we can add a property value like this

object.property="value"

The value is you encapsulate the field. In this case a caller can change the port and you have no control over the values of it:

public int Port;

In the case of a property you can do sanity checking on the new value to ensure the change is valid for the program and the operation's state.

private int _port;

    public int Port
    {
      get { return _port; }
      set 
      {
        if ((value < 0) || (value > 65535))
          throw new Exception("Invalid port value");
        _port = value; 
      }
    }

You can also remove the set accessor to add a read only property:

private int _recordId;
    public int RecordId
    {
      get { return _recordId; }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.