Block scope. : Variable Scope : Language Basics C# Examples


C# Examples » Language Basics » Variable Scope »

 

Block scope.









    
using  System;  
  
class  Example  {  
    public  static  void  Main()  {  
        int  x;  //  known  to  all  code  within  Main()  
  
        x  =  10;  
        if(x  ==  10)  {  //  start  new  scope
            int  y  =  20;  //  known  only  to  this  block  
  
            //  x  and  y  both  known  here.  
            Console.WriteLine("x  and  y:  "  +  x  +  "  "  +  y);  
        }  
        //  y  =  100;  //  Error!  y  not  known  here    
  
        //  x  is  still  known  here.  
        Console.WriteLine("x  is  "  +  x);  
    }  
}
    
   
  
   



Output

x and y: 10 20
x is 10


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Language Basics
» Variable Scope