Initializing and Assigning Variables in C#

  • C#
  • 1 min read

In C#, declare a variable by giving its type and then its name. The following is an example of initializing an integer variable and assigning a value to it.

C# Variable Initialization and Assigning Value Example

using System;
using System.Collections.Generic;
using System.Text;

namespace InitializingVariables
{
    class Program
    {
        static void Main(string[] args)
        {
            int myInt = 5;
            System.Console.WriteLine("Initialized, myInt: {0}", myInt);

            myInt = 9;
            System.Console.WriteLine("After assignment, myInt: {0}", myInt);
            Console.ReadLine();
        }
    }
}

Output

Initialized, myInt: 5
After assignment, myInt: 9

Assigning Value Without Initializing Example

using System;
using System.Collections.Generic;
using System.Text;

namespace InitializingVariables
{
    class Program
    {
        static void Main(string[] args)
        {
            int myInt;
            System.Console.WriteLine("Initialized, myInt: {0}", myInt);

            myInt = 7;
            System.Console.WriteLine("After assignment, myInt: {0}", myInt);
            Console.ReadLine();
        }
    }
}

The above program will give an error because variable myInt not yet initialize and we are trying to print.

See also: