Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thoughts on the use of readonly for any/all instance members of a class?

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(); }
    ...
}
like image 496
csharptest.net Avatar asked Sep 15 '09 18:09

csharptest.net


People also ask

What is the readonly keyword used for?

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.

What is the purpose of read-only in C#?

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.

What is readonly?

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.

Can you add items to a readonly list C#?

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.


1 Answers

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.

like image 65
JaredPar Avatar answered Sep 29 '22 02:09

JaredPar