Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
Jon B Avatar asked Oct 20 '08 21:10

Jon B


2 Answers

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;}
like image 73
Marc Gravell Avatar answered Sep 28 '22 04:09

Marc Gravell


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; }
}
like image 42
Brendan Enrick Avatar answered Sep 28 '22 03:09

Brendan Enrick