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

read­only

A vari­able declared with the read­only mod­i­fier can only be assigned as part of the dec­la­ra­tion or in the class’s constructor:

private static readonly string _defaultString = "Hello World";

const

A vari­able declared with the const mod­i­fier must be ini­tial­ized as part of the dec­la­ra­tion, and its value can­not be modified:

private const string DefaultString = "Hello World";

read­only vs const

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

Eval­u­a­tion Time Per­for­mance Type Restric­tions Scope
read­only Run­time Slow None Instance or Static
const Compile-Time Fast Prim­i­tive types, enums or strings Sta­tic

As you can see, though const is faster, read­only offers much more flex­i­bil­ity. As Bill Wagner’s stated in his first Effec­tive C# book:

A slower, cor­rect pro­gram is bet­ter than a faster, bro­ken program

which is why he’s rec­om­mended you should pre­fer read­only to const. But you must be won­der­ing how using the const mod­i­fier can ‘break’ your program!?

Well, with const, the value of the vari­able is eval­u­ated at compile-time and as I men­tioned in my post on the volatile mod­i­fier here, the com­piler will apply con­stant prop­a­ga­tion and replace any ref­er­ence to the con­stant vari­able with its value in the gen­er­ated IL code, and this hap­pens across assem­blies! This behav­iour intro­duces a sub­tle bug when you update the value of a con­stant vari­able and the updated value is not reflected in other assem­blies (because the con­stant vari­able is not eval­u­ated at run­time) until you rebuild the assem­blies which ref­er­ences this con­stant variable.

Share