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.
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.
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);
}
}AmyName is an auto-implemented property that can be set and read like a field.
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);
}
}0The 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.
