James Monger James Monger - 2 months ago 9
Vb.net Question

Linq Select compiling differently between C# and VB

I have the following C# code which compiles correctly:

private string formatterCSharp(int number)
{
return "n" + number;
}

private void testInCSharp()
{
IEnumerable<int> list = new List<int>();

IEnumerable<string> formatted = list.Select(formatterCSharp);
}


As you can see,
formatted
should contain the contents of
list
, with
formatterCSharp
applied to each.

When I try to replicate this code in VB, I come up with this:

Private Function formatterVisualBasic(ByVal number As Integer) As String
Return "n" + number
End Function

Private Sub testInVB()
Dim list As IEnumerable(Of Integer) = New List(Of Integer)

Dim formatted As IEnumerable(Of String) = list.Select(formatterVisualBasic)
End Sub


However I get two compilation errors on the
Select
statement in VB.

BC30455
Argument not specified for parameter 'number' of 'Private Function formatterVisualBasic(number As Integer) As String'.

BC30518
Overload resolution failed because no accessible '[Select]' can be called with these arguments:
Extension method 'Public Function [Select](Of TResult)(selector As Func(Of Integer, TResult)) As IEnumerable(Of TResult)' defined in 'Enumerable': Type parameter 'TResult' cannot be inferred.
Extension method 'Public Function [Select](Of TResult)(selector As Func(Of Integer, Integer, TResult)) As IEnumerable(Of TResult)' defined in 'Enumerable': Type parameter 'TResult' cannot be inferred.

Answer

Try

Dim formatted As IEnumerable(Of String) = list.Select(AddressOf formatterVisualBasic)

In VB.net you can't specify function name to pass it like that.

https://msdn.microsoft.com/en-us/library/y72ewk2b.aspx

Comments