Exercise 3-9 (StaticFun, Increment static field)

Chapter_3     Exercise_3-8 StaticField     Exercise_3-10







Exercise 3-9     TCS, p. 86


Exercise 3-9. Turn the StaticFun code fragments into a working program.




Increment.cs     TCS, p. 70-71


public class Increment
{
public class StaticTest // inner class
{
public static int i = 47;
}

public class StaticFun // inner class
{
public static void Increment()
{ // access static field in a static context:
StaticTest.i++;
}
}

public static void Main()
{
StaticTest st1 = new StaticTest();
StaticTest st2 = new StaticTest();
// System.Console.WriteLine("st1.i = " + st1.i); // compile errors
// System.Console.WriteLine("st2.i = " + st2.i);
System.Console.WriteLine("StaticTest.i = " + StaticTest.i);
StaticFun sf = new StaticFun();
// sf.Increment(); // compile error
StaticFun.Increment();
System.Console.WriteLine("StaticTest.i = " + StaticTest.i);
// new StaticFun().Increment(); // compile error
StaticTest.i++; // access static field in a static context, Main()
System.Console.WriteLine("StaticTest.i = " + StaticTest.i);
// new StaticTest().i++; // compile error
}
}
/*
mcs Increment.cs
// 3 warnings: st1, st2, sf not used

mono Increment.exe
StaticTest.i = 47
StaticTest.i = 48
StaticTest.i = 49
*/









Chapter_3     Exercise_3-8 BACK_TO_TOP StaticField     Exercise_3-10



Comments

Popular posts from this blog

Contents