ruben450
ruben450

Reputation: 140

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

I am using linq in a simple console application and I get this error and can't figure out what is wrong. Never got this error before with linq.

public class Program
{
    public static List<string> names = new List<string>();
    static void Main(string[] args)
    {
        names.Add("Ruben");
        names.Add("Dirk");
        names.Add("Jan");
        names.Add("Klaas");

        var test = names.SingleOrDefault(x => x.EndsWith("k"));
    }
}

enter image description here

Upvotes: 0

Views: 10940

Answers (2)

Hasan Manzak
Hasan Manzak

Reputation: 663

This is completely normal. It happens when predicate parameter is optimized out when code is compiled and not available to the debugger. When you continue to run the highlighted statement you should see the test variable is evaluated, if there're no other exceptions, which I'm referring to SingleOrDefault() call, it throws an exception when you have multiple results of the predicate test.

And also, as @klaus-gütter mentioned the variables in LINQ expressions are visible in the expression execution only, when they're not optimized out.

Upvotes: 0

Klaus G&#252;tter
Klaus G&#252;tter

Reputation: 11997

The x variable is only visible within the LINQ expression itself. So while the debugger is on the assignment statement var test = names.SingleOrDefault... you won't see it. You can set a breakpoint on x.EndsWith("k") then you will see the x value when it is hit.

Upvotes: 3

Related Questions