S
S
sswwssww2021-06-05 16:30:39
C++ / C#
sswwssww, 2021-06-05 16:30:39

Is it possible to reinitialize variables in C#?

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int a = 0; a < 3;a++)
            {
                Console.WriteLine(a);
            }

            int a = 3;
        }
    }
}

- I get the error: "Local variable or parameter named 'a' cannot be declared in this scope because this name is used in the enclosing local scope to define a local variable or parameter"

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int a = 0; a < 3;a++)
            {
                Console.WriteLine(a);
            }

            a = 3;
        }
    }
}

- and so: "The name "a" does not exist in the current context."
How do I use "a" or variables in C# one-time? :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
ayazer, 2021-06-05
@sswwssww

{
    var k = 0;
    {
        var k = 5;
    }
}
{
    {
        var k = 5;
    }
    var k = 0;
}

It's better to look at this example. from the compiler's point of view, these are equivalent situations
. in the internal visibility zone, a situation arises that 2 variables with the same name are declared (I'm now talking from the point of view of parsing the source code when building ast). It doesn't matter that the variable in the top scope hasn't even been initialized yet . Potentially - yes, it could work differently, but (it seems that) it was decided that the benefits of this complication (allowing in the internal context to declare already existing variables, provided that they have not yet been initialized in all external contexts) do not justify themselves. In addition, if you really need to do something like that (which is a rather rare situation in itself) - this can be handled with handles, i.e.
for (int a = 0; a < 3; a++)
{
    Console.WriteLine(a);
}

{
    int a = 3;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question