Java vs. C#

Scope


Java
 
class A {}
class Test
{
    public static void main(String[] args) {
        String A = "hello, world";
        String s = A;                                
        Class t = new A().getClass();    
        System.out.println(s);  // writes "hello, world"
        System.out.println(t);  // writes "class A"
    }
}

class Test { double x; void F(boolean b) { x = 1.0; if (b) { int x = 1; } } }

C#
 
class A {}
class Test
{
    static void Main() {
        string A = "hello, world";
        string s = A;          // expression context
        Type t = typeof(A);    // type context
        Console.WriteLine(s);  // writes "hello, world"
        Console.WriteLine(t);  // writes "A"
    }
}

class Test { double x; void F(bool b) { x = 1.0; if (b) { int x = 1;//error } } } compile-time error because x refers to different entities within the outer block. The following is OK class Test { double x; void F(bool b) { if (b) { x = 1.0; } else { int x = 1; } } } because the name x is never used in the outer block