The out
parameter does not work in C#. Why?
Here is my code:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var hashSet = new HashSet<int>(2);
Console.WriteLine(hashSet.Contains(2));
}
public ListNode ReverseList(ListNode head)
{
helper(head, out var newHead);
return newHead;
}
private ListNode helper(ListNode current, out ListNode newHead)
{
newHead = null;
if (current == null)
{
return null;
}
var next = helper(current.next, out newHead);
if (next == null)
{
newHead = current;
}
else
{
next.next = current;
}
return current;
}
}
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}
Here is the error I am getting:
Compilation error (line 13, col 30): ) expected
Compilation error (line 13, col 37): ; expected
Compilation error (line 13, col 37): Invalid expression term ')'
I have spent 2 hours straight trying to figure out what is wrong. Help me, please.
Here is my code online.
I tried your sample at dotnet fiddle and it seems like the compiler (version) matters. I got the same exception when running your code on the .NET 4.7.2 compiler, but when you change the compiler to Roslyn 3.8 or .NET 5 the sample works.