Field Keyword in C#

Field Keyword in C# with Examples

In this article, I will discuss the Field Keyword in C# with Examples. Please read our previous article discussing Interface Support for Ref Struct Types in C# with Examples.  In C# 13, a new keyword, field, has been introduced to clarify field access in properties. This new feature helps resolve certain ambiguities when working with automatic properties and provides greater clarity when accessing fields directly within a class or struct.

The field keyword makes the code more readable and safer, especially when working with property-backed fields that have custom logic for getting and setting their values.

What is the field Keyword?

The field keyword explicitly refers to the backing field of a property in cases where the field and the property are both named the same, or when the property access logic needs to access or modify the backing field directly. It can also be used inside properties to avoid ambiguity when dealing with a property’s getter and setter.

The field keyword helps you specify that you want to directly access the backing field (the variable behind the property), ensuring that you are not accidentally referencing the property.

Before C# 13

Before C# 13, when defining properties with backing fields in classes or structs, if the field and property names were the same, there was an ambiguity about whether you were referring to the field or the property. In such cases, the compiler would have trouble distinguishing between the field and the property inside the property accessors (getter or setter). This ambiguity could lead to potential mistakes or unclear code.

New Feature in C# 13: The field Keyword

With C# 13, you can now explicitly reference the backing field of a property using the field keyword. This allows you to avoid ambiguity and ensure you’re explicitly working with the field, not the property.

  • field = value; // Sets the backing field explicitly
  • return field; // Returns the backing field explicitly
Restrictions with the field Keyword
  • Not Allowed for Read-Only Properties: The field keyword can only be used within the setter and getter of a read-write property. It is not allowed in read-only properties because those properties do not have a setter.
  • Property Backing Field: You can only use the field keyword within the property body to reference its backing field, not outside.
Example Scenario: Using the field to avoid ambiguity

Let’s imagine you are building a class with a Temperature property, and you want to ensure that the field keyword is used when accessing the backing field directly inside the getter and setter.

namespace CSharp13NewFeatures
{
    public class Program
    {
        static void Main()
        {
            try
            {
                var temp = new Temperature(25);
                Console.WriteLine($"Temperature: {temp.TemperatureInCelsius} °C");

                temp.TemperatureInCelsius = 30;  // Set new temperature
                Console.WriteLine($"Updated Temperature: {temp.TemperatureInCelsius} °C");

                // This will throw an exception as it's below absolute zero
                temp.TemperatureInCelsius = -300;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }

    public class Temperature
    {
        private int _tempInCelsius;  // Backing field for the Temperature property

        public int TemperatureInCelsius
        {
            get
            {
                return _tempInCelsius;  // Direct access to the backing field
            }
            set
            {
                if (value < -273)
                    throw new ArgumentException("Temperature cannot be below absolute zero.");

                field = value;  // Explicitly use the 'field' keyword to refer to the backing field
            }
        }

        // Constructor to initialize temperature
        public Temperature(int initialTemp)
        {
            TemperatureInCelsius = initialTemp;  // Initialize using property
        }
    }
}
Code Explanation:
  • Backing Field: We have a private field _tempInCelsius that backs the TemperatureInCelsius property. The TemperatureInCelsius property has a getter and setter that access the _tempInCelsius field.
  • Using field: Inside the setter of the TemperatureInCelsius property, field = value; explicitly references the backing field instead of the property itself. This is possible because of the field keyword introduced in C# 13.
  • Avoiding Ambiguity: If the setter used just _tempInCelsius = value; instead of field = value;, it would still work. But the field keyword makes the code explicit and clearer, particularly when the property and field names are the same.
  • Exception Handling: The setter throws an ArgumentException if the value passed to TemperatureInCelsius is below absolute zero.
Output:

Field Keyword in C# with Examples

Example: Using a field in Property with Validation

Now, let’s extend this with a property that involves validation. We will ensure that the setter uses the field keyword for clearer code.

namespace CSharp13NewFeatures
{
    public class Product
    {
        private decimal _price;  // Backing field for Price

        public decimal Price
        {
            get { return _price; }  // Direct access to the backing field
            set
            {
                if (value < 0)
                {
                    throw new ArgumentException("Price cannot be negative.");
                }

                field = value;  // Using the field keyword to set the backing field
            }
        }

        public Product(decimal initialPrice)
        {
            Price = initialPrice;
        }
    }

    public class Program
    {
        static void Main()
        {
            try
            {
                var product = new Product(100);
                Console.WriteLine($"Product Price: {product.Price}");

                product.Price = 150;  // Setting a new price
                Console.WriteLine($"Updated Product Price: {product.Price}");

                product.Price = -50;  // This will throw an exception as price cannot be negative
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}
Code Explanation:
  • Product Class: We have a Price property that uses _price as its backing field. The setter of the Price property performs a validation to ensure the price is not negative.
  • Using field: In the setter of the Price property, we use the field keyword to assign the value to the backing field _price. This ensures that the setter works directly with the field, providing clarity and avoiding ambiguity.
  • Exception Handling: The setter for the Price property throws an ArgumentException if the price is set to a negative value.
Output:

Benefits of Using the field Keyword in C#

Benefits of Using the field Keyword in C#:
  • Clarity: The field keyword ensures no ambiguity between the property and its backing field, especially when the field and property names are the same. This enhances code clarity.
  • Memory Efficiency: By using ref struct types or other stack-allocated types as properties and backing fields, you can ensure efficient memory usage without incurring the overhead of heap allocations.
  • Reduced Errors: The field keyword makes it easier to manage properties with complex logic, such as validation or custom logic, while ensuring you are working directly with the backing field.
  • Ref Safety: This feature allows working safely with ref struct types, provides stack-allocated properties, and maintains ref safety.

The field keyword introduced in C# 13 makes the code more explicit and clearer, especially when working with properties and backing fields. By ensuring no ambiguity, this new feature enhances code quality, reduces errors, and provides better memory efficiency when working with ref struct types. This feature is especially useful in scenarios like e-commerce systems, where data validation is critical and clarity in code is a priority.

In the next article, I will discuss Extension Properties and Indexers in C# with Examples. In this article, I explain the Field Keyword in C# with Examples. I would like your feedback. Please post your feedback, questions, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *