C# Error CS0841 – Cannot use local variable ‘{0}’ before it is declared

C# Error

CS0841 – Cannot use local variable ‘{0}’ before it is declared

Reason for the Error & Solution

Cannot use local variable ‘name’ before it is declared.

A variable must be declared before it is used.

Example of a variable used before declaration

The following example generates CS0841:

// cs0841.cs
using System;

public class Program
{
    public static void Main()
    {
        j = 5; // CS0841
        int j;
    }
}

Correct the error by moving the declaration before usage

Move the variable declaration before the line where the error occurs.

using System;  

public class Program
{
    public static void Main()
    {
        int j;
        j = 5;
    }
}

Example of a variable shadowing a type

In the following example, the intent was comparing parameter with MyEnum.A. Because a local variable declared later with the same type name, it shadows the type MyEnum and MyEnum in this method no longer refers to the enum, but refers to the declared local variable.

using System;

public enum MyEnum
{
    A, B, C
}

public class C
{
    public void M(MyEnum parameter)
    {
        // error CS0841: Cannot use local variable 'MyEnum' before it is declared
        if (parameter == MyEnum.A)
        {
            return;
        }

        // Change the variable to 'myEnum' to avoid shadowing the 'MyEnum' type.
        // This change also aligns with the C# coding conventions.
        var MyEnum = parameter;
        Console.WriteLine(MyEnum.ToString());
    }
}

Leave A Reply

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

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...