Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An auto-implemented property is a concise syntax in C# that allows you to declare a property without explicitly defining a backing field. When the compiler encounters an auto-implemented property, it automatically generates a private, anonymous backing field that can only be accessed through the property’s get and set accessors.

Basic Syntax

To declare an auto-implemented property, you define the accessors without providing an implementation body.
public string FirstName { get; set; }
Under the hood, the C# compiler translates the above declaration into an equivalent standard property with a hidden backing field. The generated code logically resembles the following:
[CompilerGenerated]
private string <FirstName>k__BackingField;

public string FirstName
{
    get { return <FirstName>k__BackingField; }
    set { <FirstName>k__BackingField = value; }
}

Accessor Accessibility

You can apply access modifiers directly to individual accessors to restrict visibility. The accessor modifier must be more restrictive than the property’s overall access level.
// The property can be read publicly, but only modified from within the defining class.
public int RecordId { get; private set; }

// The property can be read publicly, but only modified by the defining class or derived classes.
public decimal Balance { get; protected set; }

Inline Initialization (C# 6.0+)

Auto-implemented properties can be assigned a default value directly at the point of declaration. This initializes the underlying compiler-generated backing field before the class constructor executes.
public string Status { get; set; } = "Pending";
public int RetryCount { get; set; } = 3;

Read-Only Auto-Properties (C# 6.0+)

You can declare an auto-implemented property with only a get accessor. The compiler generates a readonly backing field, meaning the property can only be assigned a value during inline initialization or within the class constructor.
public class DatabaseContext
{
    public Guid CorrelationId { get; } = Guid.NewGuid();

    public string ConnectionString { get; }

    public DatabaseContext(string connectionString)
    {
        // Valid assignment for a get-only auto-property
        ConnectionString = connectionString; 
    }
}

Init-Only Properties (C# 9.0+)

By replacing the set accessor with the init keyword, you create an auto-implemented property that can only be assigned a value during object creation (via an object initializer) or within the constructor. After initialization, the property itself cannot be reassigned. This enforces shallow immutability; if the property holds a reference type, the internal state of the referenced object can still be modified.
public string ConfigurationHash { get; init; }
Master C# with Deep Grasping Methodology!Learn More