When to use get; set; in c#

Basically, in that case, there is no difference, of the (many) advantages of using a property is the ability to add Events to your property, like so:

  public delegate void ChangedEventHandler(object sender, EventArgs e);

  int m_i = 0;
  public int i 
  {
      get { return m_i; }
      set { m_i = value; iChanged(self, null); }
  }

  public ChangedEventHandler iChanged;

This allows for code to know when I has been changed (there might be some syntax errors, I haven’t focused on C# in a while, but the idea is similar). This is extremely important in winforms, as this is the major way of knowing when a button (or similar) has been clicked.


Also, this allows for additional functionality in the setter of a property, e.g. checking if it is in a certain range, like this:

  int m_i = 0;
  public int i {

  get { return m_i; }
  set { if (value > 10) throw new Exception("I cannot be greater than 10!"); m_i = value; }
  }

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)