Start learning free

LESSON 188 OF 674 · C# ESSENTIALS

Properties: get and set in C#

Lesson

A class is a blueprint that bundles related data into one value. So far every value you used lived in its own variable — name here, level there. A class lets you say: a Player HAS a name and a level, and every player object carries its own copies:

class Player {
    public string Name { get; set; }
    public int Level { get; set; }
}

var hero = new Player();
hero.Name = "Ana";              // runs the hidden setter
Console.WriteLine(hero.Name);   // runs the hidden getter

Look closely at public string Name { get; set; }. That is not a plain variable — it is an auto-property. The { get; set; } tail tells the compiler to generate a hidden storage field plus two tiny methods: a getter that runs whenever someone reads hero.Name, and a setter that runs whenever someone assigns to it. From the outside it reads exactly like a field, but because every access secretly goes through a method, you can later add validation or logging without changing a single caller. That is why idiomatic C# exposes data as properties, not public fields.


Computed properties — and the trap.

Now drop the set; entirely and replace the body with =>. You get a computed property with an expression body — it stores nothing at all and recomputes its value from other properties on every read:

public int Power => Level * 25;   // read-only: recomputed on every read

The => means: "when someone reads Power, evaluate this expression". Change Level and the next read of Power is automatically up to date — a computed value can never go stale.

But a computed property has a getter and NOTHING else. Try to assign to it and the compiler stops you cold:

hero.Power = 9000;
error CS0200: Property or indexer 'Player.Power' cannot be assigned to -- it is read only

Read the error literally: only a property with a set accessor may stand on the left of =. When you catch yourself wanting to SET a computed property, set the data it is computed FROM instead — raise Level, and Power follows by itself.


Assignment
Follow the Coding Tutorial and build the class both ways — stored and computed:

  • define a class Player,
  • give it two auto-properties: Name (a string) and Level (an int), each with { get; set; },
  • add a computed property Power with the expression body => Level * 25,
  • in Run, create var hero = new Player();, set Name to "Ana" and Level to 4,
  • print the name, the level and the power.

The exact expected output is:

name = Ana
level = 4
power = 100

Hint
{ get; set; } is storage the outside world can read and write; => is a value recomputed on every read. You never set Power — you set Level and let Power answer Level * 25.


STEP 1 OF 11
    Ctrl + Enter to check