Skip to content

Instantly share code, notes, and snippets.

@emoacht
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emoacht/d3a48dde69a0c8b8eb22 to your computer and use it in GitHub Desktop.
Save emoacht/d3a48dde69a0c8b8eb22 to your computer and use it in GitHub Desktop.
Difference of ?? (null-coalescing) operator in C# and If operator in VB
public void TestMethod(IEnumerable<string> names)
{
List<string> nameList = names as List<string> ?? names.ToList(); //OK
int nameCount = (names as List<string> ?? names.ToList()).Count; //OK
//Case 1
nameList.ForEach(x => Console.WriteLine(x)); //OK
//Case 2
(names as List<string> ?? names.ToList()).ForEach(x => Console.WriteLine(x)); //OK
}
Public Sub TestMethod(names As IEnumerable(Of String))
Dim nameList As List(Of String) = If(TryCast(names, List(Of String)), names.ToList()) 'OK
Dim nameCount As Integer = If(TryCast(names, List(Of String)), names.ToList()).Count 'OK
'Case 1
nameList.ForEach(Sub(x) Console.WriteLine(x)) 'OK
'Case 2 a
If(TryCast(names, List(Of String)), names.ToList()).ForEach(Sub(x) Console.WriteLine(x)) 'Syntax Error
'Case 2 b
(If(TryCast(names, List(Of String)), names.ToList())).ForEach(Sub(x) Console.WriteLine(x)) 'Syntax Error
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment