Inside .Net readonly

The common language runtime in .Net Framework supports two kind of fields – readonly and read/write fields. As name suggests, value in the read/write fields can be assigned as many times as one wants; On the other hand, value in the readonly field can not be changed after it get initialized in type/instance contructor of the type containing the readonly.

Depending on the type of the readonly field – static/intance– it gets initialized. Static readonly gets loaded when the dll containing the class being loaded by CLR where as  instance readonly field got initialized when the constructor get called for the particular instance. In the following code – Bullet1 gets initialized when the InsideReadonly first gets loaded in CLR –

public class InsideReadonly
{

     public static readonly string Bullet1 = “\u2022”;

}
 

Whereas Bullet1 gets initialized when InsideReadonly readonlyObject = new InsideReadonly(); line get executed –

public class InsideReadonly
{       
     public readonly string Bullet1 = “\u2022”;
}

The versioning problem that I discussed in my last post- Inside .Net Constants(https://adilakhter.wordpress.com/2007/12/09/inside-net-constants/) can be easily solved by using one of the above code block replacing the constant with readonly. Changing the value of the readonly field Bullet1 with a new value and building the .dll makes the application load the new values , given that versioning policy of the .DLL assembly always add the newer version / the assembly is not strongly typed.

By saying all these, I would like to make one point about the readonly fields – whenever we want to use it – we need to keep in mind that, the value of the readonly field only can be ONLY assigned in either in variable declaration or in type/instance constructor –  

public class InsideReadonly
        {
            public readonly string Bullet1 = “\u2022”;            
           
public InsideReadonly()
            {
                Bullet1 = “Changed Bullet1”;//Allowed                
                
Bullet1 = “Changed Bullet11111”;//Allowed
            }
            public void TestChangeReadonly()
            {
                Bullet1 = “Change is not allowed”;// Not allowed
            }
        }
 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: