Latest Replies
Thursday
Oct232008

Const vs. readonly vs. static readonly in C# .NET

Here are the differences between C# .NET const, readonly and static readonly fields.

Constants:

  • Static by default
  • Must have compilation-time value (i.e.: you can have "A"+"B" but cannot have method calls)
  • Can be used in attributes
  • Are copied into every assembly that uses them (every assembly gets a local copy of values)
  • Could be declared within functions
  • The compiler performs some optimization by not declaring any stack space for the field

Readonly instance fields:

  • Are evaluated when instance is created
  • Must have set value by the time constructor exits

Static readonly fields:

  • Are evaluated when code execution hits class reference (i.e.: new instance is created or static method is executed)
  • Must have evaluated value by the time static constructor is done
  • You really do not want to put ThreadStaticAttribute on these (since static constructor will be executed in one thread only and it will set value for its thread; all other threads will have this value uninitialized)

Class that has only constant or readonly instance fields is considered to be prepared for the concurrency challenges of parallel computing, since it has no mutable state.

BTW, there is a simple unit-test to enforce that your classes are immutable.

Additionally you might be interested in some tips on writing the event-handling code in .NET C# from the theory category.

« Trying to switch to SquareSpace | Main | How to improve .NET code by integrating hints for ReSharper »

References (1)

References allow you to track sources for this article, as well as articles that were written in response to this article.

Reader Comments (8)

Nice post, thanks for sharing! BTW, I suppose you meant to say "constant or readonly" instead of "constant of readonly" above

November 23, 2008 | Unregistered CommenterGeorge Birbilis

Thank you for spotting the typo, George!

November 25, 2008 | Registered CommenterRinat Abdullin

Can you throw some light on what are the scenarios wherein using const would be more appropriate rather than static readonly and vice versa?

December 3, 2008 | Unregistered CommenterAshish

Ashish,

rule of thumb is simple - use constants, where you can (integers, string literals etc). If constant usage is not allowed by the compiler (i.e. you want to keep some singleton object) - use static readonly.

Rinat

PS: refactoring aid like Resharper deals with this automatically, you just need to keep an eye on the proposed refactorings.

December 3, 2008 | Registered CommenterRinat Abdullin

great article... thxs :)

December 28, 2008 | Unregistered Commenterhonour chick

The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, whereas the value of a const field is set to a compile time constant.

In the static readonly case, the containing class is allowed to modify it only

in the variable declaration (through a variable initializer)
in the static constructor (instance constructors, if it's not static)
static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.

Instance readonly fields are also allowed.

Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.

class Program

{

public static readonly Test test = new Test();

static void Main(string[] args)

{

test.Name = "Program";

test = new Test(); // Error: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)

}

}

class Test

{

public string Name;

}

-------------


The difference is that static read-only can be modified by the containing class, but const can never be modified and must be initialized to a compile time constant. To expand on the static read-only case a bit, the containing class can only modify it:


-- in the variable declaration (through a variable initializer).

-- in the static constructor (instance constructors if it's not static).

-----------

Const Keyword in C# .NET

Example: public const string abc = “xyz”;
Initialized only at declaration.
Value is evaluated at compile time and can not be changed at run time.
An attempt to change it will cause a compilation error.
Const is already kind of static.
Since classes and structs are initialized at run time with new keyword, you can’t set a constant to a class or structure. But, it has to be one of the integral types.
Readonly Keyword in C# .NET

Example: public readonly string abc;
Can be initialized in declaration code or consturctor code.
Value is evaluated at run time.
Can be declared as static or instance level attribute.
A read only field can hold a complex object by using the new keyword at run time.

April 3, 2009 | Unregistered CommenterRakesh Kumar Jaiswal

ndeed, the two types cannot be changed after they were initialized, but there are some differences between them:

* 'const' must be initialized where they are declared(at compile time), whereas 'readonly' can be initialized where it is declared or inside the constructor (ar runtime).

For example const could be used in this situation:

public class MathValues
{
public const double PI = 3.14159;
}

And readonly would be better for this case:

public class Person
{
public readonly DateTime birthDate;

public Person(DateTime birthDate)
{
this.birthDate = birthDate;
}
}

or

public class Person
{
public readonly DateTime birthDate = new DateTime(1986, 1, 24);
}

*

'const' is static, so it is shared between all instances of that class and can be accessed directly (like MathValues.PI), whereas 'readonly' is not static. As a consequence a declaration like 'static const' is illegal because const is static, but 'static readonly' is legal
*

'const' can hold only integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null (not classes or structures because they are initialized at runtime, with the 'new' keyword), whereas 'readonly' can hold complex types, structures or classes (by using the new keyword at initialization) but cannot hold enumerations

April 3, 2009 | Unregistered CommenterRakesh Kumar Jaiswal

Please check the below URL for more info.

http://stackoverflow.com/questions/55984/what-is-the-difference-between-const-and-readonly

August 22, 2011 | Unregistered CommenterPandian

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>