Field vs Property

Properties

Fields

Can assign values and receive data.

Contains data only.

Cannot be used with 2 keywords ref and out.

As a variable, it can be used with ref and out.

Defined by two expressions get and set.

There are no two expressions get and set

Contains actions to handle the field.

Unable to manage data import/export.

Usually public.

Usually kept private, all data access operations are through properties.

In C#, a field is a variable (that can be of any type) that is defined inside a class. It can be used to define the characteristics of an object or a class.

On the other hand, a property is a member of the class that provides an abstraction to set (write) and get (read) the value of a private field.

Fields

Fields, as mentioned above, are variables defined in a class. Mostly, they are declared as a private variable, otherwise, the purpose of encapsulation and abstraction would be compromised.

public class Person
{
    private int age;
    private string name; // declaration of fields
}

Properties

Properties are also called accessor methods and are declared publicly inside the class. They cannot be implemented alone. They require the declaration of fields before so that they can then read or write them accordingly.

The following shows the program with properties being used:

using System;
public class Person{
  private int age; // Field "age" declared
  
  private string name; // Field "name" declared
  
  public int Age{ // Property for age used inside the class
  
    get{        // getter to get the person's age
      return age; 
    }
  
    set{        // setter to set the person's age
      age = value;
    }
  
  }
  
  public string Name{ // Property for name used inside the class
  
    get{              // getter to get the person's name
      return name;
    }
  
    set{            // setter to set the person's name
      name = value;
    }
  
  }
}

public class Program{
  
  public static void Main()
  {
  
    Person p1 = new Person();
  
    p1.Age = 25; // setting the age. Note that Property "Age"
                  // is used and not the field "age" as it is private 
  
    Console.WriteLine("Person Age is : {0}", p1.Age); // printing person's age

    p1.Name = "Bob";

    Console.WriteLine("Person Name is: {0}", p1.Name); // printing person's name

  }
}

Explanation

  • Line 2: We declare a class named Person.

  • Lines 3–5: We declare two fields named age and name. We mostly declare the fields privately.

  • Lines 7–30: We define the properties Age and Name that contain the setters and getters to read and write the age (field) and name (field), respectively.

  • Line 37: We declare an instance p1 of the defined class.

  • Lines 39 and 44: The property Age and Name sets the value for the field age and name respectively.

  • Lines 42 and 46: The property Age and Name gets and prints the value of the field age and name respectively.

Last updated