Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; }
}
like image 872
dotnetnoob Avatar asked Aug 15 '13 10:08

dotnetnoob


2 Answers

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.

like image 101
MarcinJuraszek Avatar answered Nov 15 '22 11:11

MarcinJuraszek


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)

like image 20
Heslacher Avatar answered Nov 15 '22 10:11

Heslacher