Home All Groups Group Topic Archive Search About

Is type inference required with linq?

Author
20 Nov 2007 5:40 PM
Chris Dunaway
When using linq queries, is it *required* to use type inference?

I was reviewing some linq samples and came across this one:

public void Linq5() {
    string[] digits = { "zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine" };

    var shortDigits = digits.Where((digit, index) => digit.Length <
index);

    Console.WriteLine("Short digits:");
    foreach (var d in shortDigits) {
        Console.WriteLine("The word {0} is shorter than its value.",
d);
    }
}

What exactly is the return type of the digits.Where call?  Is
shortDigits a list of strings?  And if so, are you required to use
type inference when using linq or can you explicitly specify the type?

For example, could the line above be replaced with this:

    List<string> shortDigits = digits.Where((digit, index) =>
digit.Length < index);

Similarly in the foreach line, since in this simple example, it's
obvious that the type is a string could you use this:

    foreach (string d in shortDigits)

I can't type this in to try it myself as I don't have VS2008 installed
here (yet!).

Thanks,

Chris

Author
20 Nov 2007 7:38 PM
Mattias Sjögren
Show quote Hide quote
>I was reviewing some linq samples and came across this one:
>
>public void Linq5() {
>    string[] digits = { "zero", "one", "two", "three", "four", "five",
>"six", "seven", "eight", "nine" };
>
>    var shortDigits = digits.Where((digit, index) => digit.Length <
>index);
>
>    Console.WriteLine("Short digits:");
>    foreach (var d in shortDigits) {
>        Console.WriteLine("The word {0} is shorter than its value.",
>d);
>    }
>}

This is a VB group :)


>What exactly is the return type of the digits.Where call? Is
>shortDigits a list of strings?  And if so, are you required to use
>type inference when using linq or can you explicitly specify the type?

The standard Where query operator returns an IEnumerable<T>, in this
case IEnumerable<string>.

You're only required to use var when you can't specify the type
yourself, i.e. when dealing with anonymous types.


>Similarly in the foreach line, since in this simple example, it's
>obvious that the type is a string could you use this:
>
>    foreach (string d in shortDigits)
>

Yes, and to me it makes no sense to replace string with var in this
case.


Mattias

--
Mattias Sjögren [C# MVP]  mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Author
20 Nov 2007 8:19 PM
Chris Dunaway
On Nov 20, 1:38 pm, Mattias Sjögren <mattias.dont.want.s***@mvps.org>
wrote:

Thanks for the answers.

>
> This is a VB group :)
>

My apologies.  That's twice I've posted in the wrong group today.
I've been going back and forth and I wasn't where I thought I was.
The holiday can't come soon enough!!

Chris