C# Variables Examples

Learn Variables in C# using these step by step examples.

Program.cs

using System;

namespace VariablesExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string firstName;             // declares a variable  
            string secondName;             // declares another variable  

            const int age = 87; // this assigns value to age variable
            firstName = "John"; //Assign value
            secondName = "Doe"; //Assign value
            var fullName = firstName + " " + secondName; //Create a new variable

            Console.WriteLine("FULL NAME: " + fullName); //show contents of a variable

            Console.WriteLine("AGE: "+age);
            Console.ReadKey();
        }
    }
}

Result

FULL NAME : John Doe
AGE: 87

Example 2: Block Scope

Learn scoping in C# using this example.

Program.cs

using System;

namespace BlockScopeExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int a; // known to all code within Main() 

            a = 10;
            if (a == 10)
            { // start new scope
                int b = 20; // known only to this block 

                // a and b both known here. 
                Console.WriteLine("a: " + a + " b: " + b);
            }
            // b = 100; // Error! b not known here  

            // a is still known here. 
            Console.WriteLine("a is " + a);
            Console.ReadKey();
        }
    }
}

RESULT

a: 10 b: 20
a is 10

Related Posts