C# ยท Chapter 30 of 46

C# Fields & Properties

Fields are variables declared directly inside a class to store data. Properties wrap fields with get and set accessors, allowing controlled access to a class's data, such as validation logic.

Using properties instead of public fields is considered best practice in C#, since it lets you add logic later (like validation) without changing how other code accesses the data.

Syntax
private type _field;
public type Property { get; set; }

Fields

A field is a variable declared inside a class, often marked private to restrict direct outside access, following the principle of encapsulation.

Properties

A property looks like a field from the outside but uses get and set accessors internally. Auto-implemented properties, like `public int Age { get; set; }`, provide a compact syntax.

Example 1 (csharp)
using System;

class Person {
  public string Name { get; set; }
}

class Program {
  static void Main() {
    Person p = new Person();
    p.Name = "Amy";
    Console.WriteLine(p.Name);
  }
}
Output
Amy

Name is an auto-implemented property that can be set and read like a field.

Example 2 (csharp)
using System;

class BankAccount {
  private double balance;
  public double Balance {
    get { return balance; }
    set { if (value >= 0) balance = value; }
  }
}

class Program {
  static void Main() {
    BankAccount acc = new BankAccount();
    acc.Balance = -50;
    Console.WriteLine(acc.Balance);
  }
}
Output
0

The setter rejects negative values, so balance stays at its default value of 0.

Key points

  • Fields store data directly inside a class.
  • Properties use get/set accessors to control access to data.
  • Auto-implemented properties provide a compact get; set; syntax.
  • Properties allow adding validation logic without breaking calling code.
๐Ÿ’ก Note: A common convention is to make fields private and expose them through public properties.

๐Ÿ“ Quick Quiz

1. What do properties use to control access to data?

2. Why prefer properties over public fields?

3. What is an auto-implemented property?