Tuesday 6 September 2016

Variable in C#

 

Variable

Consider a situation where you have to create a program that accepts two numbers from a user and displays the sum of the numbers on the screen. Now, while reading the numbers provided by the user, you need to store these numbers somewhere in the memory so that you can perform the add operation on the numbers. You can store the numbers in the memory by using variables.

We can say thar variables are the bukket which is use to store the information.

Naming Variables in C#

In C#, the following rules are used for naming variables:

  • A variable name must begin with a letter or an underscore („_‟), which may be followed by a sequence of letters, digits (0-9), or underscores. The first character in a variable name cannot be a digit.
  • A variable name should not contain any embedded spaces or symbols,such as ? ! @ # + - % ^ & * ( ) [ ] { } . , ; : " ' / and \.
  • However, an underscore can be used wherever a space is required, like High_Score.
  • A variable name must be unique. For example, to store four different numbers, four unique variable names need to be used.
  • A variable name can have any number of characters.
  • Keywords cannot be used as variable names. For example, you cannot declare a variable named class as it is a keyword in C#.

"C# is a case-sensitive language. This means that the TennisPlayerName variable is not the same as the tennisplayername variable. In other words, Uppercase letters are considered distinct from lowercase letters."

You can declare and initialize variables by using the following syntax:

<data_type> <variable_name>=<value>;

In the preceding syntax, the <data_type> represents the kind of data type that will be stored in a variable and <value> specifies the value that needs to be stored in the variable.

Consider the following statement that declares a variable:

int age = 1;

The preceding statement declares a variable named age of the int data type. In addition, the statement initializes the variable with the value, 1. The int data type is used to store numeric data (integers).

Consider the following statement:

char choice='y';

The preceding statement declares the variable choice of the char data type and initializes the variable with the value, y.