Tuesday, May 3, 2016

CSharp Constants

What are constants

A constant also refers to name assigned to a memory in your computer like a variable but with a subtle difference; its value can only be assigned once. Yes, the value is assigned to the memory at compile time and it cannot be changed.




How do we declare constants in C#


Exactly like you declare variables but you put one extra prefix "const" to your declaration.

This is a variable declaration with assignment.

int speedOfLight = 299792458; /*meters per sec*/

You can change the value of the above variable.

speedOfLight = 670616629; /*miles per hour*/

This is a constant declaration with assignment.

const double pi = 3.14159265358979323846264338327950;

Assignment to a constant will cause a compile time error as you can only assign values to variables, properties or indexers.

Here comes the concept of lvalue and rvalue. Look at the example below:

lvalue = rvalue
x = 10; 

The lvalue is an expression that can be placed on the left or right of the expression.

In the expression x=10, the lavlue is x and rval is 10
x will have no problem if you write
int y = x; 

The rvalue of the expression can only be placed on the right side of the expressions.
So, if you write 10=x, this would not compile as 10 is not a variable, its a literal which can only sit on the right side.


No comments:

Post a Comment