Java vs. C#

static context


Java
 
class Test
{
    int x;
    static int y;
    void F() {
        x = 1;        // Ok, same as this.x = 1
        y = 1;        // Ok, same as Test.y = 1
    }
    static void G() {
        y = 1;        // Ok, same as Test.y = 1
    }
    public static void main(String[] args) {
        Test t = new Test();
        t.x = 1;    // Ok
        t.y = 1;    // Ok
        Test.y = 1;   // Ok
    }
}

class C { private static void F() { System.out.println("C.F"); } public static class Nested { public static void G() { F(); } } } class Test { public static void main(String[] args) { C.Nested.G(); } }
circular definition class Test { static int a = b + 1;//illegal forward reference static int b = a + 1; public static void main(String[] args) { System.out.println("a = "+a+" b = "+b); } } //no compilation
static field initialization class Test { public static void main(String[] args) { System.out.println(B.Y + A.X); } public static int f(String s) { System.out.println(s); return 1; } } class A { public static int X = Test.f("Init A"); } class B { public static int Y = Test.f("Init B"); } prints: Init B Init A 2
java has no static constructor class Test { public static void main(String[] args) { System.out.println(B.Y + A.X); } public static int f(String s) { System.out.println(s); return 1; } } class A { A(){} public static int X = Test.f("Init A"); } class B { B(){} public static int Y = Test.f("Init B"); } prints: Init B Init A 2

C#
 
class Test
{
    int x;
    static int y;
    void F() {
        x = 1;   // Ok, same as this.x = 1
        y = 1;   // Ok, same as Test.y = 1
    }
    static void G() {
        y = 1;        // Ok, same as Test.y = 1
    }
    static void Main() {
        Test t = new Test();
        t.x = 1;  // Ok
        t.y = 1;  // Error, cannot access static member through instance
        Test.y = 1;  // Ok
    }
}

class C { private static void F() { Console.WriteLine("C.F"); } public class Nested { public static void G() { F(); } } } class Test { static void Main() { C.Nested.G(); } }
circular definition class Test { static int a = b + 1; static int b = a + 1; static void Main() { Console.WriteLine("a = {0}, b = {1}", a, b); } } prints: a = 1 b = 2
static field initialization using System; class Test { static void Main() { Console.WriteLine("{0} {1}", B.Y, A.X); } public static int f(string s) { Console.WriteLine(s); return 1; } } class A { public static int X = Test.f("Init A"); } class B { public static int Y = Test.f("Init B"); } prints: or Init A Init B Init B Init A 1 1 1 1
use static constructor using System; class Test { static void Main() { Console.WriteLine("{0} {1}", B.Y, A.X); } public static int f(string s) { Console.WriteLine(s); return 1; } } class A { static A() {} public static int X = Test.f("Init A"); } class B { static B() {} public static int Y = Test.f("Init B"); } the output must be: Init B Init A 1 1