Variable Scopes

Variable Scope in C# have a scope. The scope tells where the variable is available or where in the program it can be accessed. For example, variables declared inside a method can only be accessed inside that method’s body. We can have two variables with similar names as long as they exist in different methods. The program below demonstrates this concept.

using System;

namespace VariableScopeDemo
    public class Program
        static void DemonstrateScope()
            int number = 5;

            Console.WriteLine("number inside method DemonstrateScope() = {0}", number);

        public static void Main()
            int number = 10;


            Console.WriteLine("number inside the Main method = {0}", number);

Example 1

number inside method DemonstrateScope() = 5
number inside the Main method = 10

You can see that even if we declared two variables with the same name, they are in different scopes. Each of them was assigned different values. The variable inside the Main() method is not related to the variable inside the method DemonstrateScope(). We will learn more about this when we reach the topic of classes.

Written by compitionpoint

Leave a Comment

Your email address will not be published. Required fields are marked *