Is it possible to have a private setter in base class set from derived class without being public?

StackOverflow https://stackoverflow.com/questions/18250531

  •  24-06-2022
  •  | 
  •  

Pregunta

Is it possible to give private access to a base class setter and only have it available from the inheriting classes, in the same way as the protected keyword works?

public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass()
    {
        // Want to allow MyProperty to be set from this class but not
        // set publically
        public MyProperty = "abc";
    }
}

public class MyBaseClass
{
    public string MyProperty { get; private set; }
}
¿Fue útil?

Solución

Why don't you use protected?

public string MyProperty { get; protected set; }

protected (C# Reference)

A protected member is accessible within its class and by derived class instances.

Otros consejos

You only need to make the setter as protected like:

public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass()
    {
        // Want to allow MyProperty to be set from this class but not
        // set publically
        MyProperty = "abc";
    }
}

public class MyBaseClass
{
    public string MyProperty { get; protected set; }
}

See also Access Modifiers (C# Reference)

Use protected instead of private.

Protected is the right approach, but for the sake of discussion, it's possible to set a private property this way:

public class MyDerivedClass : MyBaseClass
{
    public MyDerivedClass() : base(myProperty: "abc") { }
}

public class MyBaseClass
{
    public string MyProperty { get; private set; }

    public MyBaseClass(string myProperty) { 
        this.MyProperty = myProperty;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top