variable scope in C#

Hi Expert,

How I can access test value in Other class?
class Program
    {
       
        static int test= 0;

        public Program()
        {
           
            test = 10;
        }


	public static void Main()
        {

         }

}


Class Other

{
 int i =Program.test 

}

Open in new window

LVL 1
dshi15Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Russ SuterSenior Software DeveloperCommented:
You need to make the variable Public.

Also, it's not a good idea to expose the variable directly. Best practice is to create the variable privately then use a property Get / Set to expose it publicly.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
To give you a visual representation of what Russ is stating; consider the following:
using System;

namespace EE_Q28680679
{
	class Program
	{
		public static int test = 0;

		static void Main(string[] args)
		{
			test = 10;
			Other o = new Other();

			Console.WriteLine(o.i);
			Console.ReadLine();
		}
	}

	class Other
	{
		public int i = Program.test;
	}
}

Open in new window

Produces the following output -Capture.JPGThe above, however, is bad design.  Instead you should use something like the following:
using System;

namespace EE_Q28680679
{
	class Program
	{
		private static int test = 0;

		static void Main(string[] args)
		{
			test = 10;
			Other o = new Other(test);

			Console.WriteLine(o.I);
			Console.ReadLine();
		}
	}

	class Other
	{
		private int i;

		public int I
		{
			get { return i; }
			set { i = value; }
		}

		public Other(int i)
		{
			this.i = i;
		}
	}
}

Open in new window

Which produces the same output as above.

-saige-
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.