C Sharp Variable

A variable is nothing but a name given to a storage location. Variables are naming containers used to storing data value and then refer to the data simply by naming the container. When you create variable, it creates holds space in the memory that is used for storing temporary data. As we  know about c# data types, each data type has predefined size. Before you use a variable in a CSharp program, you must declare it.
The basic value types provided in C# can be categorized as:

Type
Example
Integral types
sbyte, byte, short, ushort, int, uint, long, ulong, and char
Floating point types
float and double
Decimal types
Decimal
Boolean types
true or false values, as assigned
Nullable types
Nullable data types

Defining Variables
Syntax for variable definition in C# is:
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas.

Example:

int i, j, k;
char c;
float f, distance;
double d;
string name;


Initializing Variables
Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is:
variable_name = value;
Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as:
<data_type> <variable_name> = value;

Example:

int i = 3, b = 5;    /* initializing i and b. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x';        /* the variable x has the value 'x'. */


It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result.

Example on variables:

using System;

namespace Variable
{
  class Program
   {
     static void Main(string[] args)
      {
        //cretaing integer type variable
        int num1, num2, result;
        //Displaying message
        Console.WriteLine("Please enter first value");
          
        //Accepting Value in num1
        num1 = Int32.Parse(Console.ReadLine());
        //Displaying message
        Console.WriteLine("Enter second Value");
        //Accepting Value
        num2 = Int32.Parse(Console.ReadLine());
 
        result = num1 + num2; //processing value
 
        Console.WriteLine("Add of {0} and {1} is {2}",              num1, num2, result); //Output
 
        Console.ReadLine();
      }
   }
}

Output:
Please enter first value
5
Enter second Value
7
Add of 5 and 7 is 12

Accepting Values from User
The Console class in the System namespace provides a function ReadLine() for accepting input from the user and store it into a variable.
For example,
int i;
i = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format.

Comments