ch3-Shadow (Variable shadowing)
Chapter_3 UnInitialized | HelloDate |
CONTENTS: Shadow.cs SimpleShadow.cs
Note: Compare to Shadow on the blog Thinking_in_Java, Chapter_3.
Shadow.cs
public class Shadow // variable shadowing or name masking
{
static int i; // uninitialized fields are set to 0
public static void Main()
{ // scope of Main(), outer scope
// access static field in a static context, Main():
System.Console.WriteLine("uninitialized static int: " + i); // Shadow.i
System.Console.WriteLine("uninitialized static int: " + Shadow.i);
// int i = 1; // compile error: used before this definition (in outer scope)
{ // begin local scope
int i = 1; // shadow Shadow.i (local i not used before, in outer scope)
System.Console.WriteLine("local variable: " + i);
System.Console.WriteLine("static field: " + Shadow.i);
// System.Console.WriteLine("static field: " + new Shadow().i); // compile error
} // end local scope
} // end scope of Main(), outer scope
}
/*
mcs Shadow.cs
// 1 warning: `Shadow.i' is never assigned to, defaults to 0
mono Shadow.exe
uninitialized static int: 0
uninitialized static int: 0
local variable: 1
static field: 0
*/
SimpleShadow.cs
// file name can be different from the name of public class
public class Shadow // variable shadowing or name masking
{
static int i; // uninitialized fields are set to 0
public static void Main()
{
int i = 1; // shadow Shadow.i
System.Console.WriteLine("local variable: " + i);
System.Console.WriteLine("static field: " + Shadow.i);
// System.Console.WriteLine("static field: " + new Shadow().i); // compile error
}
}
/*
mcs SimpleShadow.cs
// 1 warning: `Shadow.i' is never assigned to, defaults to 0
mono SimpleShadow.exe
local variable: 1
static field: 0
*/
Chapter_3 UnInitialized | BACK_TO_TOP | HelloDate |
Comments
Post a Comment