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

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

  •  03-07-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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;}

OTHER TIPS

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; }
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top