C# Readonly Fields: The Truth
I recently seen this surface in some code I’ve been working on. I had to really think about this one to remember what it was. I knew it was similar to the const keyword but didn’t remember the difference. I don’t like being stumped so I looked it up. MSDN had the following to say about readonly:
Note,The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants as in the following example:
public static readonly uint l1 = (uint) DateTime.Now.Ticks;
So readonly fields can be variable based on the constructor. Also, readonly is a runtime constant and const is a compile time constant. I am not sure which is faster. That is a topic for another discussion. Below I have pasted an example of readonly in action.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | using System; namespace ReadOnlyExample { class ReadOnlyExample { public readonly int importantValue; public ReadOnlyExample(int a, int b) { importantValue = a * b; } public ReadOnlyExample(int a, int b, int c) { importantValue = a + b + c; } } class Program { static void Main(string[] args) { ReadOnlyExample example = new ReadOnlyExample(5, 4); ReadOnlyExample example2 = new ReadOnlyExample(1, 2, 3); //example.importantValue = 4; // The compiler will not accept this statement. Console.WriteLine("Important value is {0}", example.importantValue); Console.WriteLine("Important value is {0}", example2.importantValue); Console.Read(); } } } |
The output:
Important value is 20
Important value is 6
Important value is variable based on the constructor. I can think of a few instances where this is useful. Hopefully it maybe useful to you one day.
