#1,105 – Re-Declaring a Class-Level Variable within a Method

You can re-declare a class-level variable within a method, that is–declare a local variable having the same name as a class-level variable.  Within the scope of the method, the local variable will hide the class-level variable.

    public class MyClass
    {
        public int x = 10;

        public void MethodA()
        {
            double x = 4.2;
            Console.WriteLine(x);
        }
    }

1105-001
You cannot, however, reference a class-level variable before declaring the local variable, since this is interpreted as referencing the local variable before it is defined.

        public void MethodA()
        {
            // ERROR: Can't use local variable before it's declared
            Console.WriteLine(x);

            double x = 4.2;
            Console.WriteLine(x);
        }

You also can’t reference the class-level variable in an outer scope.

        public void MethodA()
        {
            Console.WriteLine(x);

            if (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday)
            {
                // ERROR: Can't declare local variable within this scope
                double x = 4.2;
                Console.WriteLine(x);
            }
        }
Advertisements

#171 – if/else Statement Can Have One or More Statements in Body

The if/else statement can be used to execute a single statement in both the if and the else part, or to execute a block of statements.  A block of statements can be executed if curly braces ({, }) are used.

            // Example 1 - block of statements
            if (age >= 50)
            {
                Console.WriteLine("Hey, you should consider joining AARP!");
                DisplayDetailsOfAARPMembership();
            }
            else
            {
                Console.WriteLine("You're still a young pup");
                DisplayInfoAboutVideoGames();
            }

            // Example 2 - single statements
            if (airfare < 850.00)
                BookTickets();
            else
                PlanARoadTrip();

            // Example 3 - mixed
            if (married)
            {
                KeepPlaceClean();
                RaiseKids();
                LearnInterpersonalSkills();
            }
            else
                PlayVideoGames();