Saturday, November 14, 2009

Spiritually reborn beauty


This month Royal Enfiled launches Royal Classic 350cc and 500cc motorcycle in India. If you are interested in Royal Enfield Please do visit you nearest dealer station. The look and feel is the same with new technology added to the old Royal Classic.
I am very eager to ride this machine.

readonly vs const

what is readonly and const

in .net there are two types of constant. runtime and compile time. readonly are runtime constant and const are compile time.
1. which one is faster? const are faster than readonly. reason is straight forward const are get assign at compile time and when you see the IL code you can see direct value assign there. while in case of readonly, reference get attached there.
2. which one to use ?
const you can assign to string, number data types. so limitation is here.
consider following example.

const Myclass1 cls = new Myclass1();

will this code complile ? NO
you will get following error

Error 1 'cls' is of type 'ConsoleApplication1.Myclass1'. A const field of a reference type other than string can only be initialized with null.

So you can not use const here.
try above using readonly...
great !!!
3. in 1st scenario... const are faster that readonly ....
suppose in your application you dont have 2nd scenario. and in your application you care about the speed. so you will use const.
consider following scenario.
have one class library.

public class Helper
{
public static readonly int StartValue = 5;
public const int EndValue = 10;
}

My another assembly say MyApp i uses above class library with taking reference in the application.

for(int i = Helper.StartValue; i < Helper.EndValue; i++)\
{
Console.WriteLine("Value is {0}",i);
}
output:
Value is 5
Value is 6
.
.
Value is 9

now i will change the code in my Helper class as follows.
public class Helper
{
public static readonly int StartValue = 105;
public const int EndValue = 120;
}

and recompile the Helper class library. and copy past the reference copy in my assembly MyApp without recompiling the MyApp assembly.
(use two different project here. one for Helper class library and another for assembly MyApp )
what will be the final output ?
You will get no output....
to know the result check il code for MyApp.
in IL direct value get assign to const variable where are for readonly reference is there.
so your for loop will take StartValue= 105 and EndValue = 10.
So you need to consider scenario 3 while declaring variable with readonly that const.
My suggestion
It is better to use slower but secure program than faster, broken program.

Thanks,
Prashant M