Like any other languages, C# has its own rules to declare variables. Variables are naming containers used to storing data value and then refer to the data simply by naming the container. Before you use a variable in a CSharp program, you must declare it.
abstract | add | as | ascending | async | await | base | bool |
break | by | byte | case | catch | char | checked | class |
const | continue | decimal | default | delegate | descending | do | double |
dynamic | else | enum | equals | explicit | extern | false | finally |
fixed | float | for | foreach | from | get | global | goto |
group | if | implicit | in | int | interface | internal | into |
is | join | let | lock | long | namespace | new | null |
object | on | operator | orderby | out | override | params | partial |
private | protected | public | readonly | ref | remove | return | sbyte |
sealed | select | set | short | sizeof | stackalloc | static | string |
struct | switch | this | throw | true | try | typeof | uint |
ulong | unchecked | unsafe | ushort | using | value | var | virtual |
void | volatile | where | while | yield |
The scope of a variable is the region of source code in which it is defined. In C# a global variable has global scope; it is defined outside method in C# code. On the other hand, variables declared within a method are defined only within the body of the method. They are local variables and have local scope.
In C# a local variable to be declared within any block, a block beginning with opening brace and ends with a closing curly brace. As a general rule, a local variable declared inside a scope are not visible outside the scope.
Within the body of a method, a local variable takes precedence over a global variable if decleaded with same name. If variables are declared as local or method parameter with the same name as a global variable, effectively hide the global variables:
There are situations when we require to assign one variable value to other variable. In C#, all type are not compitable hence all type conversions are not implicitly possible for example int variable can be assigned to float variable because they are compatible and int variable can implicitly be converted to float variable but wice versa is not possible because destination type range should be greater than source type range.
But if required, non compitable types can also be converted using a cast, since cast perform explicit type conversion.
From | Can be convered To |
---|---|
sbyte | short,int,long, float,double,decimal |
byte | short,ushort,int,uint, long,ulong,float,double,decimal |
short | int,long,float,double,decimal |
ushort | int,uint,long,ulong, float,double,decimal |
int | long,float,double,decimal |
uint | long,ulong,float,double,decimal |
long | float,double,decimal |
char | ushort,int,uint,long,ulong,float,double,decimal |
float | double |
ulong | float,double,decimal |