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.

A protected field in C# is a class-level variable declared with the protected access modifier, restricting its visibility strictly to the declaring class and any types derived from it. It establishes an inheritance-based encapsulation boundary, preventing direct access from external, non-derived types while exposing the internal state to subclasses.
public class BaseClass
{
    protected int _protectedField;
}

Accessibility Rules

The protected modifier enforces compile-time access checks based on the inheritance hierarchy, regardless of assembly boundaries.
  • Declaring Class: Full access.
  • Derived Class (Same Assembly): Full access.
  • Derived Class (Different Assembly): Full access.
  • Non-Derived Class: Inaccessible (Compiler Error CS0122).

Cross-Instance Access Constraints (CS1540)

A critical mechanical rule of protected fields in C# is that a derived class can only access a protected field through an instance of its own type or a type derived from it. It cannot access the protected field through an instance of the base class or a different derived class.
public class BaseClass
{
    protected int _identifier;
}

public class DerivedClass : BaseClass
{
    public void EvaluateAccess()
    {
        // Valid: Implicit access to 'this._identifier'
        _identifier = 1; 

        // Valid: Access via an instance of the exact derived type
        DerivedClass derivedInstance = new DerivedClass();
        derivedInstance._identifier = 2;

        // Invalid: Access via an instance of the base type
        BaseClass baseInstance = new BaseClass();
        // baseInstance._identifier = 3; // Compiler Error CS1540
    }
}

public class SiblingClass : BaseClass
{
    public void EvaluateSiblingAccess(DerivedClass sibling)
    {
        // Invalid: Access via an instance of a different derived type
        // sibling._identifier = 4; // Compiler Error CS1540
    }
}

Structural Limitations

  • Structs: Because C# struct types do not support inheritance, declaring a protected field inside a struct is syntactically invalid and results in Compiler Error CS0666.
  • Static Modifiers: A field can be declared protected static. In this case, the field belongs to the type itself rather than an instance. Derived classes can access the protected static field directly via the type name or implicitly, and the CS1540 instance-access rule does not apply.
  • Memory Layout: The protected keyword is purely a compile-time visibility constraint. At runtime, a protected field occupies memory within the object instance exactly like a private or public field.
Master C# with Deep Grasping Methodology!Learn More