none
Real world use cases for using readonly modifier ? RRS feed

Answers

  • Greetings Natasha.

    Suppose you are dealing with prefabricated wall panels (as I do in my line of work). Each panel consists of multiple pieces of timber called 'members' that are nailed together to make a wall - studs, nogs, lintels on windows and doors, and so on. Each member has a 2D polygon that shows where it fits in the panel.

    Now, if you are in a module which allows the user to edit panels by shifting things around, changing the thickness of timbers, cutting notches out of timbers to hold other bits and pieces, and so on, then the polygons must be editable.

    If, however, you are in a downstream module where the user is reading the fully-designed panels and sending them to machinery for manufacture, you definitely don't want the polygons to be editable. In that case, readonly is the go.

    Does that help?

    Monday, September 2, 2019 5:42 AM
  • My example would be where you are setting the "personality" of a class. For example, if you had a generic chat bot class, which could be instantiated as a sales bot, or a customer support bot. You create the type of bot in the constructor, passing in a "sales" or "support" enum. From that point on, everything the class does is for that personality and no reason the personality would change. So personality is read only. That's exactly what I used it for before anyway. You could say inheriting from a base class would be another way, but the only difference to my bots was which set of adaptive cards (chat script) it pulled from SQL, which was an id (int) matching the (int)enum. So having a bunch of inherited classes was overkill. Having a read only property was all it required.

    All the best,
    Pete


    #PEJL
    Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over to TechNet Wiki, for future generations to benefit from! You'll never get archived again, and you could win weekly awards!

    Have you got what it takes to become this month's TechNet Technical Guru? Join a long list of well known community big hitters, show your knowledge and prowess in your favoured technologies!


    Monday, September 2, 2019 7:25 PM
    Moderator
  • Hi,

    I will use readonly fields for injected dependencies for my classes.

    So whenever I use the dependency injection design pattern, and I am injecting dependencies via the constructor, they will be assigned to a readonly member. This makes it possible for my class to use the dependency, but not to change it during its lifetime.

    https://blogs.msdn.microsoft.com/chrisgarty/2004/05/31/safer-c-constructor-based-dependency-injection-with-readonly/

    Kind regards,

    Johnny Hooyberghs

    Tuesday, September 3, 2019 6:15 AM

All replies

  • Hello,

    Ask a handful of programmers this question and you will get several responses. I would recommend reading through the following discussion.

    https://stackoverflow.com/questions/277010/what-are-the-benefits-to-marking-a-field-as-readonly-in-c


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Proposed as answer by EckiS Sunday, September 1, 2019 5:59 AM
    Sunday, September 1, 2019 1:23 AM
    Moderator
  • It's a good idea to limit access to the fields of a type wherever possible, especially setting the value of fields.  If you only set the value once when constructing the object, then it is useful to limit that ability to just one place if you can.  It's a little less that can go wrong when you know it's only set once.

    There's no performance benefit, but it's a code maintenance issue - it makes your job easier when you limit access as much as possible.


    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter

    Sunday, September 1, 2019 8:53 PM
  • I appreciate all the answers which add additional clarification to Microsoft docs but what I am looking for is a real world example where readonly is the obvious choice over a regular field.

    Thanks 

    Monday, September 2, 2019 2:52 AM
  • Any time you are setting a field in the constructor, for example, and it doesn't change after that:

    I have many classes where this happens:

    class Foo
    {
        private readonly int Bar;
    
        public Foo(int bar)
        {
            Bar = bar;
        }
    
        //'Bar' is used but never set anywhere else
    }



    Convert between VB, C#, C++, & Java (http://www.tangiblesoftwaresolutions.com)
    Instant C# - VB to C# Converter
    Instant VB - C# to VB Converter

    Monday, September 2, 2019 2:57 AM
  • Hi Dave, 

    Thanks for the prompt response. I totally get that readonly field cannot be assigned after constructors exists or in other words the functionaliy of this modifier is SUPER clear by now. I am curious if anyone is willing to give a short description of a real-world project where readonly was preferred over a regular field.  Thanks

    Monday, September 2, 2019 5:22 AM
  • Greetings Natasha.

    Suppose you are dealing with prefabricated wall panels (as I do in my line of work). Each panel consists of multiple pieces of timber called 'members' that are nailed together to make a wall - studs, nogs, lintels on windows and doors, and so on. Each member has a 2D polygon that shows where it fits in the panel.

    Now, if you are in a module which allows the user to edit panels by shifting things around, changing the thickness of timbers, cutting notches out of timbers to hold other bits and pieces, and so on, then the polygons must be editable.

    If, however, you are in a downstream module where the user is reading the fully-designed panels and sending them to machinery for manufacture, you definitely don't want the polygons to be editable. In that case, readonly is the go.

    Does that help?

    Monday, September 2, 2019 5:42 AM
  • Hi Ante

    Yes, this does help. This is exactly the use case I was looking for.

    So, I am assuming in the wall configuration part the "shifting things around, changing the thickness of timbers"  means assigning  or re-assigning fields within a constructor and in order to make those field assignments in stone down the stream a choice was given to readonly field. 



    Monday, September 2, 2019 6:09 PM
  • My example would be where you are setting the "personality" of a class. For example, if you had a generic chat bot class, which could be instantiated as a sales bot, or a customer support bot. You create the type of bot in the constructor, passing in a "sales" or "support" enum. From that point on, everything the class does is for that personality and no reason the personality would change. So personality is read only. That's exactly what I used it for before anyway. You could say inheriting from a base class would be another way, but the only difference to my bots was which set of adaptive cards (chat script) it pulled from SQL, which was an id (int) matching the (int)enum. So having a bunch of inherited classes was overkill. Having a read only property was all it required.

    All the best,
    Pete


    #PEJL
    Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over to TechNet Wiki, for future generations to benefit from! You'll never get archived again, and you could win weekly awards!

    Have you got what it takes to become this month's TechNet Technical Guru? Join a long list of well known community big hitters, show your knowledge and prowess in your favoured technologies!


    Monday, September 2, 2019 7:25 PM
    Moderator
  • Hello again Natasha.

    In the office there is one application, for inputting, editing, and designing buildings. So the user inputs all the walls according to the plan. Then the customer says ' Can we put a door in that wall to connect those two rooms?", and the user edits the model of the building accordingly. So at this stage, everything must be editable.

    When the customer is satisfied, and places an order for the finished product, the fully designed model is sent to the factory via database or xml files or whatever (it depends on a couple of things) where it can be read by different applications that drive saws, presses, conveyor belts, and so on. In these applications, we don't want anything about the building to change, so everything is readonly. (I was using the polygon as an example, but really it's the whole thing.) I mean, it's fairly obvious that a saw shouldn't be able to edit the data it's reading, it should just be doing what it's told, but making things readonly makes sure there can't be any accidents.

    Monday, September 2, 2019 11:22 PM
  • Hi,

    I will use readonly fields for injected dependencies for my classes.

    So whenever I use the dependency injection design pattern, and I am injecting dependencies via the constructor, they will be assigned to a readonly member. This makes it possible for my class to use the dependency, but not to change it during its lifetime.

    https://blogs.msdn.microsoft.com/chrisgarty/2004/05/31/safer-c-constructor-based-dependency-injection-with-readonly/

    Kind regards,

    Johnny Hooyberghs

    Tuesday, September 3, 2019 6:15 AM
  • Thank you everyone for your answers. It was very helpful. 


    Friday, September 6, 2019 2:58 AM