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.


CSharp Variables

What are variables in general


In any programming language, a variable refers to a space in the computers memory. We give this space a meaningful name so that we can refer to that memory in our code easily without causing any confusion. 




Assigning a value to a variable means that we intend to put a value in the memory identified by the variable.


How to declare variables in C#


The syntax in C# to declare a variable is to first write the type and then its name like so:


typeOfVariable nameOfVariable;

            int counter;
            string name;
            double price;



Declare and Assign a value at the same time



You can declare and assign the value to a variable in a signle step like so:

typeOfVariable nameOfVariable = thevalueofthevariable;

These are some good examples of variable declarations with value assignment.

            int counter = 0;
            string name = "Your Name";
            double price = 24.99d;

These are some bad examples of variable as their names do seem to be meaningful:
            int x = 0;
            string theVariable = "Your Name";
            double p = 24.99d;