ideas | discover | explore

Tuesday, September 6, 2011

C# 3 - Variable Scope

1.  Create a new console project.
2. Modify Program.cs with the following code.

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




namespace CSharpEpisode3
{
    class Program
    {               
        static void Main(string[] args)
        {
            VariableExample variableExample = new VariableExample();
            Console.WriteLine(variableExample.GlobaVariable);
            variableExample.VariableTest();

            Console.WriteLine("Press any key to continue.....");
            Console.ReadLine();
        }
    }

    class VariableExample
    {
        public string GlobaVariable = "I'm a global variable"; //available both inside and outside this class
        private string PrivateVariable = "I'm a private variable within VariableExample class"; //available only inside this class

        public void VariableTest()
        {
            string localVariable = "I'm a local variable within VariableTest() method"; //available only within this method VariableTest()
            Console.WriteLine(localVariable);
            Console.WriteLine(PrivateVariable);
        }
    }
}



3. Press F5 to run.
4. Thank you.

No comments: