Home > other >  Cannot implicitly convert 'List<List<int>>' to 'IList<IList<int>
Cannot implicitly convert 'List<List<int>>' to 'IList<IList<int>

Time:01-30

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  ;
    }
}

CodePudding user response:

You can

var result = new List<IList<int>>();

and then make sure that whatever you put in your result list implements IList, such as:

result.Add(new List<int>());

Your code as is doesn't actually use the result so it's hard to make a suggestion

CodePudding user response:

You can only cast the outermost List to an IList. For example, this code would work:

// cast the outermost List to an IList - this works
IList<List<int>> stuff = new List<List<int>>();

However, the generic type specified for the outermost list (T = List<int> in my example above) cannot be cast, even to an interface that it implements.

This code does not work:

// cast the inner List to an IList - this is not supported
List<IList<int>> things = new List<List<int>>();

Unless there is some reason you really need to return an IList, you can simply update your function definition to return a List instead of an IList.

public List<List<int>> ThreeSum(int[] nums)

If you are interested in why this isn't supported, my opinion follows. The implicit casting of the generic types is incredibly complex to implement and is not supported in C#. To cast the generic type, the generic type constraints would have to be revalidated, every variable in memory of the type would have to be cast - which is an intensive operation fraught with opportunity for error - and it is quite possible that the casting into a new type would invalidate previous operations (e.g. through conditional pattern-matching logic) of the class containing the generic type.

  •  Tags:  
  • Related