Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't understand, why an implicit conversion of matching generic types doesn't work #201

Open
olivermue opened this issue Feb 1, 2024 · 0 comments

Comments

@olivermue
Copy link

olivermue commented Feb 1, 2024

When using FluentResults with generic types like IReadOnlyList<T> it seems that implicit conversation doesn't work and I can't understand why. Maybe someone can enlighten me by this simple example.

What works without any problems is this kind of code:

private async Task<string> FindMatchingItem()
{
    await Task.Delay(1);
    return "1";
}

public async Task<Result<string>> GetMatchingItem()
{
    var item = await FindMatchingItem();
    // Here we can simply return item, which will be automatically be converted into Result<string>
    return item;
}

But, what doesn't work is this one here:

private async Task<IReadOnlyList<string>> FindMatchingItems()
{
    await Task.Delay(1);
    return new List<string> { "1", "2", "3" };
}

public async Task<Result<IReadOnlyList<string>>> GetMatchingItems()
{
    var items = await FindMatchingItems();
    // Doesn't compile. Has to be: return Result.Ok(items);
    return items;
}

The compiler complains with this error message:
CS0266: Cannot implicitly convert type 'System.Collections.Generic.IReadOnlyList<string>' to 'FluentResults.Result<System.Collections.Generic.IReadOnlyList<string>>'. An explicit conversion exists (are you missing a cast?)

If I'm going to change the signature of FindMatchingItems() to return Task<List<string>> the error is gone:

// We changed the return type to be List instead of IReadOnlyList
private async Task<List<string>> FindMatchingItems()
{
    await Task.Delay(1);
    return new List<string> { "1", "2", "3" };
}

// But not here. It is still IReadOnlyList
public async Task<Result<IReadOnlyList<string>>> GetMatchingItems()
{
    var items = await FindMatchingItems();
    return items;
}

So can anyone explain, why List<string> can be converted into Result<IReadOnlyList<string>>, but the very same type IReadOnlyList<string> can't be converted into the desired Result type?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant