Posts Tagged ‘Private’

VBA to C#: Public, Private and Static Variables in C#

August 17, 2009

Was answering a forum question by a VBA programmer about public, private and static variables in C#. (Create a New>Project in Visual Studio 2008, and choose Visual C#>Console Application, name it PublicPrivateStatic_Test, and paste in the code below.


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

namespace PublicPrivateStatic_Test
{
    class Program
    {
        public int publicInt = 1;
        private int privateInt = 2;
        static private int privateStaticInt = 3;

        public int getPrivateInt()
        {
            return privateInt;
        } 

        public void setPrivateStaticInt(int i)
        {
            privateStaticInt = i;
        }
        public int getPrivateStaticInt()
        {
            return privateStaticInt;
        }
    }

    class OtherProgram
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Program q = new Program();

            Console.Write("Public int is {0}", p.publicInt);
            //Prints 1, as it is public

            //Console.Write("Private int is {0}", p.pirvateInt);
            //Wont Compile as it is a private variable.
            //Need to use p.getPrivateInt(). Prints 1.
            Console.Write("\nPrivate int is {0}", p.getPrivateInt());

            //Console.Write("Private int is {0}", p.pirvateStaticInt);
            //Wont Compile as it is a private variable.
            //Need to use getPrivateStaticInt(). Prints 3.
            Console.Write("\nPrivate Static int is {0}", p.getPrivateStaticInt());

            p.setPrivateStaticInt(999);
            Console.Write("\nPrivate Static int is now {0}", q.getPrivateStaticInt());
            //Will print 999 instead of 3. Think of a static variable
            //as only existing once, and p and q both reference it. If
            //instance p changes it, then it is also changed for instance q.

            //Keeps the console open until any-key pressed
            Console.ReadLine();
        }
    }
}

Console output:

Console output

Console output

Advertisements