C#.Net Variables

  • A Variable is a name given to storage area of any value in the program.
  • Variable's name is used to refer the data value stored at particular memory location.
  • The value stored in any variable can be changed at the run time.

Naming convention of a Variable in C#.Net

There are various rules which we have to know for naming a variable in C#. These rules are as given below:

  • The name of variable consists of the alphabets, digits (0-9) and underscores character (_).
  • They must not begin with the digits.
  • It cannot contains the characters like {,(,},),!,#,$,%,^,&,*,?,/,\ etc.
  • Uppercase letter and lowercase are treated distinctly at the time of naming variable because C# is a case sensitive language.
  • Keyword cannot be a name of variable. If we want to use the keyword as the name of variable then we have to use it with prefix "@".
  • Whitespaces are not allowed in the variable name.
  • Variable name can be of any length.

Here is a table which tells us about the valid or invalid variable's name:


Variable Declaration in C#.Net

  • A variable name must be declared before using it into the program.
  • It can be declare with a meaningful name of a specific data type.
  • Here is the syntax for the variable declaration:
  • datatype variable;

  • We can declare number of variables of same data type in a single line as given below:
  • datatype variable1, variable2, variable3...................variableN;

Initialization of Variables

  • After declaration of variable you need to initialize the variable.
  • It is not mandatory to initialize the variable at the time of declaration it is totally depend upon the choice of the user.
  • Variable must be initialized before its use in the program.
  • Here is the syntax for the initialization of a variable:
  • datatype variable1=value,
    datatype variable1;

  • Here are some examples of initialization of the variable:
  • int length = 5;
    float value= 100.00f;
    char c1= 'a';