There are two types of constants available in c#:
Compile-time constants and runtime constants. They have different behaviors and
using wrong one will cost you performance or correctness.
But Runtime constants are always preferable over
compile-time constants. Though the compile-time constants are slightly faster
but they are not flexible with compare to runtime constants.
The compile-time constants are preferable when performance
is really required and you don’t have any requirements to change the value of
that constant.
Compile-time constant are declared using “const” keyword:
Eg: public const int a=10;
Run-time constants are declared using “readonly” keyword:
Eg: public readonly int a=10;
compile-time – “Const” | run-time – “readonly” |
compile-time | Run-time |
compile-time | Run-time |
A compile-time constant is replaced with the value of that Eg: public const int a=10; int b=20; if(b==a) compiles to the same IL as if you had written this: if(b==10)// means instead of comparing with variable ‘a’ it | Runtime constants are evaluated at runtime. The IL generated Eg: public const int a=10; int b=20; if(b==a) compiles to the same IL as if you had written this: if(b==a)// so instead of placing its value as like it do with |
compile-time constant cannot initialize using the new operator, | runtime constants can be of any type, They must |
Compile-time constants can be used only for primitive types
These are the only types that enable you to assign meaningful
As we know that for “const” type in compiler-generated IL the | runtime Read-only values are also constants, in that they cannot be has executed. But read-only values are different in that they |
Compile-time | Run-time constants are much more flexible but its performance |
Compile-time constants are, by definition, static | readonly values can be used for instance constants, for each instance of a class type. |
Every | No need to rebuild Application assembly which is referring a |
The final advantage of using const over readonly is
performance: Known constant values can generate slightly more efficient code
than the variable accesses necessary for readonly values.
However, any gains are slight and should be weighed against the decreased
flexibility. Be sure to profile performance differences before giving up the
flexibility.
1 comment:
You could certainly see your expertise within the work you write.
The world hopes ffor even more passionate writers succh as you who are not afraid to mention how they believe.
At all times go after your heart.
Post a Comment