.Net Tips — using readonly vs const in C#

In C#, there are two ways for you to declare a con­stant vari­able, you can either declare the vari­able as read­on­ly, or con­st:


A vari­able declared with the read­on­ly mod­i­fi­er can only be assigned as part of the dec­la­ra­tion or in the class’s con­struc­tor:

private static readonly string _defaultString = "Hello World";


A vari­able declared with the con­st mod­i­fi­er must be ini­tial­ized as part of the dec­la­ra­tion, and its val­ue can­not be mod­i­fied:

private const string DefaultString = "Hello World";

readonly vs const

Here’s a quick glance of how the two mod­i­fiers dif­fer:

Eval­u­a­tion Time Per­for­mance Type Restric­tions Scope
read­on­ly Run­time Slow None Instance or Sta­t­ic
con­st Com­pile-Time Fast Prim­i­tive types, enums or strings Sta­t­ic

As you can see, though con­st is faster, read­on­ly offers much more flex­i­bil­i­ty. As Bill Wagner’s stat­ed in his first Effec­tive C# book:

A slow­er, cor­rect pro­gram is bet­ter than a faster, bro­ken pro­gram

which is why he’s rec­om­mend­ed you should pre­fer read­on­ly to con­st. But you must be won­der­ing how using the con­st mod­i­fi­er can ‘break’ your pro­gram!?

Well, with con­st, the val­ue of the vari­able is eval­u­at­ed at com­pile-time and as I men­tioned in my post on the volatile mod­i­fi­er here, the com­pil­er will apply con­stant prop­a­ga­tion and replace any ref­er­ence to the con­stant vari­able with its val­ue in the gen­er­at­ed IL code, and this hap­pens across assem­blies! This behav­iour intro­duces a sub­tle bug when you update the val­ue of a con­stant vari­able and the updat­ed val­ue is not reflect­ed in oth­er assem­blies (because the con­stant vari­able is not eval­u­at­ed at run­time) until you rebuild the assem­blies which ref­er­ences this con­stant vari­able.