Reputation: 14578
I have a C# function like this-
public IList<IList<int>> Subsets(int[] nums)
{
List<List<int>> output = new List<List<int>>();
if (nums.Length == 0)
{
return output; //Problem in this line
//return null;
}
........
........
return output.Concat(Subsets(nums.Skip(1).ToArray())).ToList();
}
What I am finding is-
Severity Code Description Project File Line Suppression State
Error CS0266
Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.List<int>>' to 'System.Collections.Generic.IList<System.Collections.Generic.IList<int>>'.
An explicit conversion exists (are you missing a cast?) LeetCode D:\LeetCode\Solution.cs 13 Active
Can anyone please help?
Upvotes: 1
Views: 1126
Reputation: 7526
Though, I agree with other answers to create appropriate interface, you can do this without creating new list like Gur Galler proposed with a little bit of hardcore hacking:
[StructLayout(LayoutKind.Explicit)]
public struct Union
{
[FieldOffset(0)]
public List<List<int>> a;
[FieldOffset(0)]
public IList<IList<int>> b;
public static IList<IList<int>> Cast(List<List<int>> list)
{
var u = new Union();
u.a = list;
return u.b;
}
}
class Program
{
static void Main(string[] args)
{
var lists = new List<List<int>>() { new List<int>() { 1, 2, 3 } };
IList<IList<int>> casted = Union.Cast(lists);
}
}
Upvotes: 0
Reputation: 14578
Thanks to @NetMage for the great comment.
I have changed
return new List<List<int>>();
to
return new List<IList<int>>();
Which works great for me.
Upvotes: 0
Reputation: 1606
Change
List<List<int>> output = new List<List<int>>();
to
List<IList<int>> output = new List<IList<int>>();
You can cast the outer list to IList, since List implements IList, but you can't force the cast of the type argument of List, so it should be declared as IList since the beginning.
Upvotes: 3
Reputation: 920
Try this:
IList<IList<int>> list2 = list.Cast<IList<int>>().ToList();
You have to add using System.Linq;
for that.
Upvotes: 2