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


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; }
        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; }
This question has already been answered. Start a new discussion instead.