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

Implicit return for Result does not allow Interface<T> - must be concrete type ie List<T> not IEnumerable<T> #354

Closed
martinbryant opened this issue Oct 28, 2021 · 2 comments

Comments

@martinbryant
Copy link

Example

public Result<Thing, string> GetThing()
{
        bool success = false;
        var thing = new Thing();
        if(!success)
            return "";
    
        return thing;
}

Compiles

public Result<IEnumerable<Thing>, string> GetThingsList()
{
    bool success = false;
    List<Thing> things = new List<Thing>() { new Thing() };
    if(!success)
        return "";

    return things;
}

Compiles

public Result<IEnumerable<Thing>, string> GetThingsIEnumerable()
{
    bool success = false;
    IEnumerable<Thing> things = new List<Thing>() { new Thing() };
    if(!success)
        return "";

    return things;
}

Does not compile - Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'CSharpFunctionalExtensions.Result<System.Collections.Generic.IEnumerable, string>'

It seems as if it does not work correctly for anything that is an Interface ie IEnumerable, IList, ICollection.

Workaround

public Result<IEnumerable<Thing>, string> GetThingsIEnumerable()
{
    bool success = false;
    IEnumerable<Thing> things = new List<Thing>() { new Thing() };
    if(!success)
        return "";

    return Result.Success<IEnumerable<Thing>, string>(things);
}
@martinbryant martinbryant changed the title Implicit return for Result does not allow IEnumerable<T> - must be concrete type ie List<T> Implicit return for Result does not allow Interface<T> - must be concrete type ie List<T> not IEnumerable<T> Oct 28, 2021
@hankovich
Copy link
Collaborator

hankovich commented Oct 28, 2021

Yes, it's a C# limitation, it has no elegant solutons/workarounds. We usually return List<Thing> via interface reference (as in your second example).

Additional info:
https://stackoverflow.com/a/143567
dotnet/roslyn#14186

@martinbryant
Copy link
Author

Ok @hankovich I appreciate you confirming that and can understand the reasoning for it.

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

2 participants