Alex Rivera | Logout

Why can't I project ToString() in VB?

Asked 2011-01-10T12:18:05.670
18

If you try to compile the query below in Visual Basic .NET, it fails.

From x In {1, 2} Select x.ToString()

The error given by the compiler is:

Range variable name cannot match the name of a member of the 'Object' class.

There is nothing wrong with the equivalent C# query, though:

from x in new[]{1, 2} select x.ToString()

This does not happen with the ToString overload that takes a format (it is a member of Int32, not Object). It does happen with other members of Object, as long as they don't take an argument: with GetType and GetHashCode it fails; with Equals(object) it compiles.

Why is this restriction in place, and what alternatives can I use?

Edit
Report

1 Answer

5

While I can't offer details about the error, a simple workaround it:

From x In {1, 2, 3} Let str = x.ToString() Select str

For what it's worth, when you have the following line:

Dim b = From num In {1, 2, 3} Select num.ToString("d")

it is compiles and decompiles to (using Reflector, to C#):

public class Class1
{
    [CompilerGenerated]
    private static string _Lambda$__1(int num)
    {
        return num.ToString("d");
    }

    public void Test1()
    {
        IEnumerable<string> b = new int[] { 1, 2, 3 }
            .Select<int, string>(new Func<int, string>(Class1._Lambda$__1));
    }
}

There doesn't seem to be any anonymous class along the way.

answered 2011-01-10T12:47:37.387

Your Answer