Preface
For some time now I've been using the readonly modifier for nearly all class fields. I use it for List<T> members, IDisposeable members, ints, strings, etc... everything but value types I intend to change. I tend to do this even when I would normally like to null a member on Dispose(). IMHO The advantages of not needing the if statements to test for null or disposed conditions greatly outweigh the 'potential' for trouble in objects that 'could' be disposed multiple times.
The Question
When do you use readonly, or do you?
Do you or your company have any best-practices and/or coding standards regarding the use of readonly?
I'm curious to hear your thoughts on the following sample class, is the general concept a good practice or not?
class FileReaderWriter : IFileReaderWriter, IDisposable
{
private readonly string _file;
private readonly Stream _io;
public FileReaderWriter(string path)
{
_io = File.Open(_file = Check.NotEmpty(path), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
public void Dispose() { _io.Dispose(); }
...
}
The readonly keyword can be used to define a variable or an object as readable only. This means that the variable or object can be assigned a value at the class scope or in a constructor only.
In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.
Read-only is a file attribute which only allows a user to view a file, restricting any writing to the file. Setting a file to “read-only” will still allow that file to be opened and read; however, changes such as deletions, overwrites, edits or name changes cannot be made.
In C# there is the readonly keyword that enforced the rule that the variable must be initialised as it's declared or in the constructor. This works as expected for simple types, but for objects and lists it's not quite like that. With a list, you can still add, remove and change items in the list.
I use readonly on fields in any situation where the code will successfully compile.
Why? Simple, if a field reference / value suddenly goes from never changing to changing it can violate subtle assumptions in the class and consumers. As such I want to be alerted to that change in order to evaluate the implications of this new behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With