C#

Properties in C#

ยท 1 min read

Like many other programming languages, C# class does have the class properties, also called fields.


Example of the class property

public class Player {

  private int experience;

  public int Experience {
    get {
        return experience;
    }
    set {
        experience = value;
    }
  }
}

// Use property 
public class GameControl: MonoBehaviour {
	void Start () {
    Player myPlayer = new Player();

    //Properties can be used just like variables
    myPlayer.Experience = 5;
    int x = myPlayer.Experience;
  }
}

To make it more concise:

public class Player {
  public int Experience {get; set;}
}

For property Experience, it has the get and set pair. You probably have seen this similar thing before, so why do we need get and set, here are the reasons:

1, use set and get can easily control a property is read-only or write-only.

Read-only: can't set value for experience

public class Player
{

  private int experience;

  public int Experience {
      get {
        //Some other code
        return experience;
      }
  }
}

Write-only: can't read/get value for experience

public class Player {

  private int experience;

  public int Experience {
    set {
        experience = value;
    }
  }
}

2, Flexibility on manipulating the write value or read value

We can get the player's level by divide their experience by 1000.

public class Player {

  private int experience;

  public int Experience {
    get {
      return experience;
    }
    set {
      experience = value;
    }
  }

  public int Level {
    get {
      return experience / 1000;
    }
    set {
      experience = value * 1000;
    }
  }
}

// To use
Player player = new Player();
player.Level;