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

Issue: var does not handle Generic anonymous functions #15661

Closed
pmunin opened this issue Dec 4, 2016 · 3 comments
Closed

Issue: var does not handle Generic anonymous functions #15661

pmunin opened this issue Dec 4, 2016 · 3 comments

Comments

@pmunin
Copy link

pmunin commented Dec 4, 2016

Expected Behavior:

var selector = (Node n) => {
     return new {Node = n, ChildrenCount = n.Children.Count };
}

Actual Behavior:

public static class Workaround
{
    public static Func<T1,TResult> Function<T1,TResult>(Func<T1,TResult> func)
    {
        return func;
    }
}

///...

var selector = Workaround.Function( (Node n) => {
     return new {Node = n, ChildrenCount = n.Children.Count };
});

@HaloFour
Copy link

HaloFour commented Dec 4, 2016

Dupe of #14 which was already closed.

In short, delegates are all different types according to the CLR and they are incompatible with each other even if their signature matches. The C# language has no special knowledge of any specific delegate types, including the Func<...> or Action<...> delegate families. If lambda inference were to decide to use Func<...>, assuming that could be done unambiguously, assigning that to a variable or parameter of a different-but-compatible signature would involve wrapping the delegate with another delegate. That doubles the overhead when invoking the delegate, each call costing about the same as a virtual instance method call, which isn't a lot but can add up in aggregate.

@aluanhaddad
Copy link

I still think this is worth reconsidering, especially if collection literals are on the table, because they will also have to somewhat arbitrarily target clandestine types that are conventionally used.

If lambda inference were to decide to use Func<...>, assuming that could be done unambiguously, assigning that to a variable or parameter of a different-but-compatible signature would involve wrapping the delegate with another delegate.

But isn't the suggestion here to only use Func<....> when it would otherwise be an error?

@CyrusNajmabadi
Copy link
Member

Closing out. This is legal now in the language.

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

No branches or pull requests

5 participants