C# Field vs Property (with Examples)

C# Field Vs Property: The main difference between a Field and a Property in C# is that a field is simply a variable of any type declared within a class or struct, whereas a property is a class member that offers a convenient way to access, modify, or calculate the value of a private field.

Fields are standard class variables, and properties are an abstraction for accessing their values.
In this tutorial, you will learn about the difference between field and property in C# and how to use them effectively.

difference between field and property in csharp
Difference between field and property in C#

What is a Field in C#?

In C#, a field is a variable declared within a class and used to store data that We can access from anywhere within the class.

The data type of a field can be int, string, bool, etc. Fields are used to characterize an object or a class. For better data management, it is recommended to declare fields as private and access their values through properties instead of directly manipulating the field values. 

This approach follows the principle of encapsulation in Object-Oriented Programming (OOP) and prevents unauthorized modification of the field values.

  • A field is a variable declared directly within a class or struct.
  • Fields store data and can be private, protected, internal, or public.
  • Unlike properties, fields do not have any access control mechanisms or data validation rules.
  • Fields are used to store data directly related to the object’s state.

Example:

The following is an example of a field in C#:

public class Person
{
    // Declare a field as a string
    private string Name;

    // Declare a field as an integer
    private int Age;

    // Declare a field as a boolean
    private bool IsMarried;

    // Declare a field as a decimal
    private decimal Salary;

    // Declare a field as a DateTime
    private DateTime Birthday;
}

In the above code, we have declared five fields of various data types: string, int, bool, decimal, and DateTime. These fields can be used to store data within the Person class.

What is a Property in C#?

A property in C# is a class member that provides access to a private field. Properties are used to encapsulate the data stored in a field and provide control over the way the data is accessed and used. Properties have accessors, get and set, that control the reading and writing of the underlying data.

Properties do not have storage locations but instead have accessors that execute the necessary commands for reading and writing values. These accessors can consist of either a get accessor or a set accessor. 

For example, consider a class called Person with a private field named “name”. Since We cannot directly access this field from outside the class, properties are used to set and retrieve its values, thereby providing a way to access the private field.

  • A property is a class member that provides a flexible mechanism to read, write, or compute the value of a private field.
  • Properties are a kind of getter and setter method, but they look like fields from the outside.
  • Properties are used to control to access data of an object and to enforce data validation rules.
  • Properties have two get and set accessors to allow for read and write access to the underlying private field.
  • Properties also have accessibility levels, like fields and methods, which can be set to public, private, protected, or internal.

Example:

The following is an example of a property in C#:

public class Person
{ 
   // private field
    private string name;
    // public property
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}
  • Properties expose the underlying private fields of a class. Maintaining the fields as private and accessing them through the use of get and set properties is advisable.
  • Properties offer a layer of abstraction that enables you to alter the private fields internally, provide control over the data, and reduce the likelihood of unintentional changes in a private field value from outside the class.

Validation check using property in C#

A property can have its logic, such as validation or computation, implemented within the get and set accessors. For example, you could add a validation check to ensure that the value being set is within a certain range:

class Employee
{ 
   // private field
    private int _age;
    // public property
    public int Age
    {
        get 
        {
            return _age;
        }
        set 
        {
            if (value >= 18 && value <= 70) 
            {
                _age = value;
            }
            else 
            {
                throw new ArgumentOutOfRangeException("Age must be between 18 to 45");
            }
        }
    }
}

Raising Events with Properties in C#

Properties can trigger a PropertyChangedEvent when the property’s value is altered or even before it is changed. On the other hand, accessing fields directly does not offer this same capability.

Example:

public class Person 
{
    // Private field to store the name
    private string _fullName;

    // Event to raise before the name is changed
    public event EventHandler NameChanging;

    // Event to raise after the name is changed
    public event EventHandler NameChanged;

    // Property to get and set the name
    public string FullName
    {
        get
        {
            return _fullName;
        }
        set
        {
            // Raise the NameChanging event
            OnNameChanging();
            _fullName = value;
            // Raise the NameChanged event
            OnNameChanged();
        }
    }

Difference between Field and Property in C#

  • Accessibility: Fields can be declared and directly accessed from anywhere within the class, while a property offers a flexible way of reading, writing, or computing the value of a private field.
  •  Encapsulation: Fields do not control the stored data, while properties encapsulate the data and control how it is accessed and used.
  •  Code Maintenance: Fields are susceptible to unintentional changes by the user, whereas properties provide control over the data and reduce the likelihood of unintentional changes.
  •  Validation: Properties provide a mechanism to validate data before it is set, while fields do not have any validation rules.
  •  Access control: Properties have a higher access control level than fields, as they contain get and set accessors to allow for read and write access. Fields can be private, protected, internal, or public, but they lack the control provided by properties.
  •  Syntax: Properties are written like methods but accessed like fields, while fields are written as variables and accessed like variables.
  •  Data Storage: Fields can be considered variables at the class level. To store data in objects of your classes, you must use fields. There is no alternative option. Properties don’t store data but get it from the field using the get accessor internally.

C# Field vs Property

FeatureFieldsProperties
Accessibility:Directly accessible from anywhere within the class.Accessible through accessors (get and set) that control the reading and writing of the underlying data
Encapsulation:Fields do not provide control over the data stored.Properties encapsulate the data and provide control over the way the data is accessed and used.
Code Maintenance:Prone to accidental changes.Provides control over the data and reduces the likelihood of accidental changes.
Data Validation:A field cannot validate data.Property can have data validation logic built into the set accessor to ensure that the data being set is valid.

Conclusion:

Properties and fields store data in C# but have different purposes and functionality. Properties control access to an object’s data and enforce data validation rules while fields store data that is directly related to the object’s state.
Understanding the differences between properties and fields will help you write better and more maintainable code in C#.

FAQs: C# Field vs Property

Q: What are properties in C#?

Properties in C# are members of a class or struct that provide a flexible mechanism to read, write, or compute the value of a private field.

Q: What are fields in C#?

Fields in C# are variables declared directly within a class or struct. They are used to store data and can be private, protected, internal, or public.

Q: What is the difference between a field and a property?

The main differences between properties and fields in C# are accessibility, validation, and syntax. Properties have a higher level of access control and provide a mechanism for validating data. At the same time, fields can be private, protected, internal, or public without validation rules.
Properties are written like methods but accessed like fields, while fields are written as variables and accessed like variables.

Q: When should you use properties in C#?

You should use properties in C# when you need to control the access of a private field and enforce data validation rules. Properties provide a flexible mechanism for reading, writing, or computing the value of a private field and allow you to ensure that data is valid before it is set to the field.

Q: When should you use fields in C#?

You should use fields in C# when you need to only store data that is directly related to the state of an object. Fields are used to store data and are written as variables and accessed like variables. Unlike properties, fields do not have any access control mechanisms or data validation rules.

Q: What are the benefits of using properties in C#?

Property in C# provides higher access control, data validation, and a more maintainable codebase. Properties provide a flexible mechanism for reading, writing, or computing the value of a private field and allow you to validate data before assigning it.
Furthermore, because properties are written like methods but accessed like fields, the code will be easier for us to understand and maintain.

References: Stackoverflow-Fields vs properties

You might also like:

We would love to hear your thoughts on this post. Please leave a comment below and share it with others.

Shekh Ali
4 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments