Monday, June 10, 2013

Variable Initialization in C#

Variable Initialization in C#

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 (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as:
  = value;
Some examples are:
int d = 3, f = 5;    /* initializing d and f. */
byte z = 22;         /* initializes z. */
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, sometime program would produce unexpected result.
Try following example which makes use of various types of variables:
namespace VariableDeclaration
{
    class Program
    {
        static void Main(string[] args)
        {
            short a;
            int b ;
            double c;

            /* actual initialization */
            a = 10;
            b = 20;
            c = a + b;
            Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
            Console.ReadLine();
        }
    }
}
When the above code is compiled and executed, it produces following result:
a = 10, b = 20, c = 30

No comments:

Post a Comment