I am new to C# and seem to be stuck at a problem. The return type of the function ThreeSum called is IList<IList> and the List being returnted is of type List<List> and I am seeing the following exception: Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.List>' to 'System.Collections.Generic.IList<System.Collections.Generic.IList>'.
Here is the code:
public IList<IList<int>> ThreeSum(int[] nums)
{
Array.Sort(nums);
var result = new List<List<int>>();
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] > 0) break;
twoSum(nums, i, result);
}
return result;
}
private void twoSum(int[] nums, int i, List<List<int>> result)
{
var seen = new HashSet<int>();
for (int j = i + 1; j < nums.Length; j++)
{
int comp = -nums[i] - nums[j];
if (seen.Contains(comp))
{
result.Add(new List<int>(){nums[i], nums[j], comp});
}
while (j < nums.Length - 1 && nums[j] == nums[j+1]) j++;
}
}
` and you would be allowed to cast it to `IList>`. Someone could then try inserting a `ArraySegment` which *is* a `IList` but is *not* a `List`. So this could never be allowed. You could cast to `IReadOnlyList>` because that is covariant and therefore assignment-compatible
– Charlieface Jan 30 '22 at 03:10