Is type inference required with linq?

  • Thread starter Thread starter Chris Dunaway
  • Start date Start date
C

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
 
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
 
On Nov 20, 1:38 pm, Mattias Sjögren <[email protected]>
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
 
Back
Top