What is the difference between const and static readonly?

Published 03 December 04 05:13 PM

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;

    }

 

On the other hand, if Test were a value type, then assignment to test.Name would be an error.

 

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# senthil said on December 13, 2004 7:43 AM:
i want explanation.
# FAQ C# said on December 19, 2004 8:40 PM:
# FAQ C# (par Yannick Lejeune) said on August 23, 2005 5:13 AM:
# What is the difference between const and static readonly? said on November 27, 2007 7:10 PM:

PingBack from http://feeds.maxblog.eu/item_802202.html

# i like ellipses… » Intent Programming said on July 16, 2008 1:37 AM:

PingBack from http://ilikeellipses.com/2008/07/16/intent-programming/

# What is the difference between const and static readonly? : F9 Group Marketing and Technology Blog said on September 17, 2008 3:28 PM:

PingBack from http://blog.f9group.com/technology/c/what-is-the-difference-between-const-and-static-readonly/

# AShu said on October 6, 2009 7:23 AM:

dIFFERENCE bETWEEN // and / in C# when using url  

# AShu said on October 6, 2009 7:23 AM:

dIFFERENCE bETWEEN // and / in C# when using url  

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

This Blog

Syndication

Page view tracker