Thursday, May 17, 2012

Java said, C# said. Scope consistency

Whereas in Java, this illegal code would become legal when you move the int i = 20 before the last line, in C# it is still illegal


class TestLoop{
   public static void main(String[] args){
 

        int i = 20;                 
        
        for (int i = 0; i < 10; i++) System.out.print(i + " ");  
        for (int i = 10; i > 0; i--) System.out.print(i + " ");  


        System.out.print(i + " ");   // last line
   }
}


Moving int i = 20; after those loops that uses the same variable name i would become legal in Java; whereas in C#, it is still illegal:

class TestLoop{
   public static void main(String[] args){
 
        
        for (int i = 0; i < 10; i++) System.out.print(i + " ");  
        for (int i = 10; i > 0; i--) System.out.print(i + " ");  

        int i = 20;                 

        System.out.print(i + " ");   // last line
   }
}

No comments:

Post a Comment