You've successfully subscribed to Hacking with Unity - Learn how to create your own games
Great! Next, complete checkout for full access to Hacking with Unity - Learn how to create your own games
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Properties in C#

Ben Liu
Ben Liu

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;

Ben Liu

Please feel free to contact me if you have any question. <br> https://t.me/NeedoneApp