Search code examples
c#readonlyprocessing-efficiencymemory-efficient

What are the benefits to marking a field as `readonly` in C#?


What are the benefits of having a member variable declared as read only? Is it just protecting against someone changing its value during the lifecycle of the class or does using this keyword result in any speed or efficiency improvements?


Solution

  • The readonly keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the const modifier, which must have its value set at compile time. Using readonly you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.

    Also use it if you don't want to have to recompile external DLLs that reference the constant (since it gets replaced at compile time).