Letβs go over fields and properties in C# β fundamental ways to store and manage data inside a class.
π 1. Fields
A field is a variable declared inside a class to hold data.
Key Points
-
Usually declared as
private
for encapsulation -
Can be
public
, but itβs better to use properties -
Stores the actual data of an object
Example
public class Person
{
public string Name; // Public field
private int age; // Private field
public void SetAge(int value)
{
if (value >= 0)
age = value;
}
public int GetAge()
{
return age;
}
}
-
Name
is a public field β accessible directly -
age
is private β accessed via methods to control changes
π 2. Properties
A property is a member that provides controlled access to a field. Can be thought of as a defined function inside a class, not to be confused with custom functions inside a class- which are called Methods. See 4.4 Methods within classes
-
Combines get (read) and set (write) accessors
-
Can include logic/validation inside get/set
-
Preferred over public fields for encapsulation
Example: Basic Property
public class Person
{
private int age;
public int Age
{
get { return age; } // Read
set
{
if (value >= 0) // Validation
age = value;
} // Write
}
}
Usage
Person person = new Person();
person.Age = 25; // Calls set accessor
Console.WriteLine(person.Age); // Calls get accessor
π 3. Auto-Implemented Properties
C# allows simpler syntax when no extra logic is needed:
public class Person
{
public string Name { get; set; } // Automatically creates a hidden backing field
}
Person person = new Person();
person.Name = "Alice";
Console.WriteLine(person.Name);
-
Automatically creates a private field behind the scenes
-
Can also make read-only or write-only:
public string Name { get; private set; } // Can only set inside the class
π 4. Properties vs Fields
Feature | Field | Property |
---|---|---|
Access | Direct | Controlled via get/set |
Encapsulation | Weak (if public) | Strong |
Validation | Must use separate methods | Can include logic in set/get |
Syntax | public int age; | public int Age { get; set; } |
Backing Field | Explicit or automatic | Can be auto-implemented |
π 5. Best Practices
-
Keep fields private and expose them via properties.
-
Use properties for validation or computed values.
-
Use auto-implemented properties for simple storage.
-
Name fields in camelCase and properties in PascalCase.
β Tip:
-
Fields = raw data
-
Properties = controlled access to data