Variable scopes in C# - Beware of naming similiarities

Just the other day I came across a sample of code with some similar named variables, where the flow did not work probably. It turned out to be an issue of some locale variables which were named the same as some global variables.

This made me think some about it and do some testing about scoping, and I created this small snippet to illustrate what can be done and what cannot be done

using System;
namespace ScopeTest
    class Program
        static void Main(string[] args)
        { new Program().Debug(); }
        int temp = 1;
        void Debug()
            int temp = 2;
            Console.WriteLine(temp); //Prints 2
            Console.WriteLine(this.temp); //Prints 1
            //Action a = delegate() //Will not compile
            //    int temp = 3;
            //    Console.WriteLine(temp);


This is just something you need to know and be aware of otherwise you might experience strange unexpected issues.

Comments are closed