How to use static variable in class with C#

1 Answer

0 votes
using System;

namespace class_static_variables
{
	public class StaticTest
	{
        public static int static_n;
        public int x;

        public StaticTest()
		{
			x++; 
			static_n++;
		}
		static public int GetStatic_n()
		{
			//x = 30; // Error: static function can access only static variables
            static_n++;
			
            return static_n;
		}
		public void Show ()
		{
			Console.WriteLine("x = {0} static_n = {1}", x, static_n);
		}
	}
	class Class1
	{
		static void Main(string[] args)
		{
			StaticTest st1 = new StaticTest();
			st1.Show(); // x = 1 static_n = 1

			StaticTest st2 = new StaticTest();
			st2.Show(); // x = 1 static_n = 2

			StaticTest st3 = new StaticTest();
			st3.Show(); // x = 1 static_n = 3

            Console.WriteLine("StaticTest.GetStatic_n() = {0}", StaticTest.GetStatic_n()); 
            //StaticTest.GetStatic_n() = 4
		}
	}
}



answered Jul 18, 2014 by avibootz
edited Jul 18, 2014 by avibootz

Related questions

2 answers 155 views
2 answers 228 views
1 answer 199 views
1 answer 191 views
1 answer 193 views
1 answer 172 views
2 answers 197 views
197 views asked Aug 25, 2018 by avibootz
...