user27414
user27414

Reputation:

What is the best way to implement a property that is readonly to the public, but writable to inheritors?

If I have a property that I want to let inheritors write to, but keep readonly externally, what is the preferred way to implement this? I usually go with something like this:

private object m_myProp;
public object MyProp
{
    get { return m_myProp; }
}
protected void SetMyProp(object value)
{
    m_myProp = value;
}

Is there a better way?

Upvotes: 10

Views: 1930

Answers (3)

Bill K
Bill K

Reputation: 62769

Having a setter and getter isn't really any better than having a variable at that level of visibility.

Therefore you could just make the variable itself protected and the reader public.

That said, setters and getters are an indicator of bad OO--are you sure you need them? You should be asking the object to do something with its members, not asking it for its members then manipulating them outside the object.

This is a very general rule and there are a lot of exceptions.

Upvotes: 0

Brendan Enrick
Brendan Enrick

Reputation: 4297

This is definitely the way to go.

public object MyProp {get; protected set;}

If you're on an older version of C# then this is the way to go.

private object _myProp;
public object MyProp
{
    get { return _myProp; }
    protected set { _myProp = value; }
}

Upvotes: 5

Marc Gravell
Marc Gravell

Reputation: 1062855

private object m_myProp;
public object MyProp
{
    get { return m_myProp; }
    protected set { m_myProp = value; }
}

Or in C# 3.0

public object MyProp {get; protected set;}

Upvotes: 36

Related Questions