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

FeatureFieldProperty
AccessDirectControlled via get/set
EncapsulationWeak (if public)Strong
ValidationMust use separate methodsCan include logic in set/get
Syntaxpublic int age;public int Age { get; set; }
Backing FieldExplicit or automaticCan be auto-implemented

πŸ“Œ 5. Best Practices

  1. Keep fields private and expose them via properties.

  2. Use properties for validation or computed values.

  3. Use auto-implemented properties for simple storage.

  4. Name fields in camelCase and properties in PascalCase.


βœ… Tip:

  • Fields = raw data

  • Properties = controlled access to data