Skip to content

/errors/csharp/cs0103-name-does-not-exist-in-current-context

C# error CS0103: The name does not exist in the current context

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · 10.0.401updated
tool
C#
exit code
1
versions
.NET 6 – 10, C# 10+
os
any

error CS0103: The name 'x' does not exist in the current context means the C# compiler found no variable, field, method or type called x that is visible where it is used. Scope is the usual cause: a variable declared inside an if, for or try block disappears when the block ends. Declare it before the block, fix a typo, or qualify a static member with its class name.

Reproduce it

bash
export DOTNET_NOLOGO=1 DOTNET_CLI_TELEMETRY_OPTOUT=1
dotnet new console -o app >/dev/null 2>&1
cd app
cat > Program.cs <<'EOF'
int[] values = { 1, 2, 3 };
if (values.Length > 0)
{
    int total = 0;
    foreach (var v in values) total += v;
}
Console.WriteLine(total);
EOF
dotnet build -nologo 2>&1 | grep -o 'error CS[0-9]*: [^[]*' | sort -u
exit ${PIPESTATUS[0]}

Output · exit 1

error CS0103: The name 'total' does not exist in the current context

total exists only between the braces of the if block, so the Console.WriteLine line cannot see it.

Fix: declare it in the outer scope

bash
export DOTNET_NOLOGO=1 DOTNET_CLI_TELEMETRY_OPTOUT=1
dotnet new console -o app >/dev/null 2>&1
cd app
cat > Program.cs <<'EOF'
int[] values = { 1, 2, 3 };
int total = 0;
if (values.Length > 0)
{
    foreach (var v in values) total += v;
}
Console.WriteLine(total);
Console.WriteLine(Math.Max(total, 10));
EOF
dotnet run

Output

6
10

Similar messages

CodeMessageDifference
CS0103The name 'x' does not exist in the current contextAn unqualified name is not visible here
CS0246The type or namespace name 'X' could not be foundA type name cannot be resolved (missing using or package)
CS1061'T' does not contain a definition for 'm'The name exists, but not as a member of that type
CS0165Use of unassigned local variable 'x'Declared but not definitely assigned before use

Sources