Some of my classes use a protected readonly field that represents a logger. Below is some sample code -
public class RunJob {
protected readonly ILogger logger;
public RunJob(ILogger logger) { this.logger = logger;}
public virtual void ProcessFiles() {
logger.Log("Start");
...
logger.Log("End");
}
}
Having gone through many articles/threads on properties vs fields, I realize that protected fields are considered bad but I'm wondering if I will gain any real practical benefits by making logger a property. Considering my use case above, is there any real difference between the below 3 -
protected readonly ILogger logger;
protected ILogger Logger { get; }
or perhaps (protected ILogger Logger {get; private set;}
- which is readonly only for subclasses)#2 backed by a private _logger object
In my application, #1 works well enough - The logger object is initialized once in the constructor and is then used throughout the class (and its subclasses), this class and its subclasses do nothing other than calling logger.Log(...) and no one except for this class and its subclasses cares whether it's a field or property.
I have gone through this thread but many questions remain unanswered -
One benefit that could've been applicable here is that the properties can be overriden, but in C# they're sealed by default (unless properties work different than methods). So, unless the developer intentionally makes a property virtual, this benefit is not applicable.
Are there any performance benefits to be gained by using a readonly field? Surely, the compiler etc would have to work a little extra to make readonly properties work?
I do see the overall benefits of properties over fields in principle and even though it's just one line of change in my case, I wonder if I'm doing it just because it's a new cool fad or whether it really truly applies in this case?