Zaid Masud Zaid Masud - 23 days ago 8
C# Question

Protected readonly field vs protected property

I have an abstract class and I'd like to initialize a readonly field in its protected constructor. I'd like this readonly field to be available in derived classes.

Following my habit of making all fields private and exposing properties, I implemented this as follows:

abstract class Foo
{
private readonly int _field;

protected Foo(int field)
{
_field = field;
}

protected int Field
{
get { return _field; }
}
}


But then I wondered if there is really much advantage of keeping the field private here. I'm aware of the advantages of properties and there are several SO questions on this issue in general, but they focus on public fields as opposed to protected ones.

So should I switch to the below implementation or not? What are the considerations and advantages/disadvantages to be aware of in either case?

abstract class Foo
{
protected readonly int _field;

protected Foo(int field)
{
_field = field;
}
}

Answer

Derived classes are still 'users' of the original code; fields should be encapsulated from them too.

You should think of base classes as safe and extendable APIs, rather than just classes which expose their internals. Keep the fields private - apart from anything, it allows the base class to change how that property's value is generated :)