In our current project, we have a very simplified version of a Result object. One of the things we are interested in adding to it is the ability to take multiple results containing an array of items and then combining them into a single result object containing all of the items from the other results.
The issue we are running into is when trying to make this generic through the IEnumerable<T>
interface, we get an error stating Cannot convert Result<string[]> to Result<IEnumerable<string>>
.
Below is a simple reproduction of the error. I know I could just add a method to handle T[]
, but is that the only option? I’m guessing this is something to do with covariance/contravariance, but I have never been good at knowing which is which and when to use what.
class Result
{
public static Result<T> Create<T>(T value) => new Result<T>(value);
public static Result<IEnumerable<T>> Flatten<T>(params Result<IEnumerable<T>>[] results)
{
return new Result<IEnumerable<T>>(results.SelectMany(x => x.Value));
}
}
class Result<T>
{
internal Result(T value) => Value = value;
public T Value { get; internal set; }
}
var result1 = Result.Create<string[]>(["A", "B"]);
var result2 = Result.Create<string[]>(["C", "D"]);
var result3 = Result.Create<string[]>(["E", "F"]);
// Should create a result of ["A", "B", "C", "D", "E", "F"]
var result = Result.Flatten<string>(result1, result2, result3);