Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In C#, a self-initializing setter can be implemented using a private field to store the value and initializing it in the constructor. The setter then checks if the private field is null and initializes it if it is:

public class MyClass
{
    private string _myProperty;

    public MyClass()
    {
        _myProperty = "default value";
    }

    public string MyProperty
    {
        get { return _myProperty; }
        set
        {
            if (_myProperty == null)
            {
                _myProperty = value;
            }
        }
    }
}

In this example, the _myProperty field is initialized in the constructor with a default value. The setter checks if _myProperty is null and initializes it with the new value if it is. This ensures that the property always has a non-null value.