30

It's possible to declare a lambda function and immediately call it:

Func<int, int> lambda = (input) => { return 1; };
int output = lambda(0);

I'm wondering if it's possible to do so in one line, e.g. something like

int output = (input) => { return 1; }(0);

which gives a compiler error "Method name expected". Casting to Func<int, int> doesn't work either:

int output = (Func<int, int>)((input) => { return 1; })(0);

gives the same error, and for reasons mentioned below I'd like to avoid having to explicitly specify the input argument type (the first int).


You're probably wondering why I want to do this, instead of just embedding the code directly, e.g. int output = 1;. The reason is as follows: I've generated a reference for a SOAP webservice with svcutil, which because of the nested elements generates extremely long class names, which I'd like to avoid having to type out. So instead of

var o = await client.GetOrderAsync(request);
return new Order {
    OrderDate = o.OrderDate,
    ...
    Shipments = o.Shipment_Order == null ? new Shipment[0]
        o.Shipment_Order.Select(sh => new Shipment {
            ShipmentID = sh.ShipmentID,
            ...
            Address = CreateAddress(sh.ReceiverAddress_Shipment);
        }).ToArray()
};

and a separate CreateAddress(GetOrderResultOrderShipment_OrderShipmentShipment_Address address) method (real names are even longer, and I have very limited control about the form), I'd like to write

var o = await client.GetOrderAsync(request);
return new Order {
    OrderDate = o.OrderDate,
    ...
    Shipments = o.Shipment_Order == null ? new Shipment[0]
        o.Shipment_Order.Select(sh => new Shipment {
            ShipmentID = sh.ShipmentID,
            ...
            Address = sh.ReceiverAddress_Shipment == null ? null : () => {
                var a = sh.ReceiverAddress_Shipment.Address;
                return new Address {
                    Street = a.Street
                    ...
                };
            }()
        }).ToArray()
};

I know I could write

Address = sh.ReceiverAddress_Shipment == null ? null : new Address {
    Street = sh.ReceiverAddress_Shipment.Address.Street,
    ...
}

but even that (the sh.ReceiverAddress_Shipment.Address part) becomes very repetitive if there are many fields. Declaring a lambda and immediately calling it would be more elegant less characters to write.

8
  • int output = ((Func<int>) (() => { return 1; }))(); Jan 17, 2020 at 10:21
  • Why not just write a small wrapper: public T Exec<T>(Func<T> func) => return func(); and use it like this: int x = Exec(() => { return 1; }); That to me reads a lot nicer than the casting with all its parens.
    – germi
    Jan 17, 2020 at 10:24
  • @germi nice idea, but it gives me "The type arguments for method Exec cannot be inferred from the usage."
    – Glorfindel
    Jan 17, 2020 at 10:28
  • @Glorfindel You did something wrong, then: dotnetfiddle.net/oku7eX
    – canton7
    Jan 17, 2020 at 10:30
  • @canton7 because I'm actually using a lambda with input parameter... Thanks, it works now.
    – Glorfindel
    Jan 17, 2020 at 10:32

6 Answers 6

30

Instead of trying to cast the lambda, I propose you use a small helper function:

public static TOut Exec<TIn, TOut>(Func<TIn, TOut> func, TIn input) => func(input);

which you could then use like this: int x = Exec(myVar => myVar + 2, 0);. This reads a lot nicer to me than the alternatives suggested here.

27

It's ugly, but it's possible:

int output = ((Func<int, int>)(input => { return 1; }))(0);

Anonymous functions, including lambda expressions, are implicitly convertible to a delegate that matches their signature, but this syntax requires the lambda to be enclosed in parentheses.

The above can be simplified as well:

int output = ((Func<int, int>)(input => 1))(0);
2
  • 2
    Ah, of course. I only tried int output = (Func<int>)(() => { return 1; })(); but the cast has lower priority than the lambda execution.
    – Glorfindel
    Jan 17, 2020 at 10:22
  • 1
    It still doesn't solve the problem of not wanting to write the extremely long class names though.
    – Glorfindel
    Jan 17, 2020 at 10:24
5

Lambda literals in C# have a curious distinction in that their meaning is dependent on their type. They are essentially overloaded on their return type which is something does not exist anywhere else in C#. (Numeric literals are somewhat similar.)

The exact same lambda literal can either evaluate to an anonymous function that you can execute (i.e. a Func/Action) or an abstract representation of the operations inside of the Body, kind of like an Abstract Syntax Tree (i.e. a LINQ Expression Tree).

The latter is, for example, how LINQ to SQL, LINQ to XML, etc. work: the lambdas do not evaluate to executable code, they evaluate to LINQ Expression Trees, and the LINQ provider can then use those Expression Trees to understand what the body of the lambda is doing and generate e.g. a SQL Query from that.

In your case, there is no way for the compiler to know wheter the lambda literal is supposed to be evaluated to a Func or a LINQ Expression. That is why Johnathan Barclay's answer works: it gives a type to the lambda expression and therefore, the compiler knows that you want a Func with compiled code that executes the body of your lambda instead of an un-evaluated LINQ Expression Tree that represents the code inside the body of the lambda.

1
  • Would be nice if int output = ((int input) => 1)(0) worked. All the type information the compiler should need is there. Would be handy for doing something like LINQ's .Select() on a scalar variable. Nov 13, 2023 at 15:32
3

You could inline the declaration of the Func by doing

int output = (new Func<int, int>(() => { return 1; }))(0);

and immediately invoking it.

2

You can also create the alias in the Select method

var o = await client.GetOrderAsync(request);
return new Order {
    OrderDate = o.OrderDate,
    ...
    Shipments = o.Shipment_Order == null ? new Shipment[0]
        o.Shipment_Order.Select(sh => {
          var s = sh.ReceiverAddress_Shipment;
          var a = s.Address;
          return new Shipment {
            ShipmentID = sh.ShipmentID,
            ...
            Address = s == null ? 
                      null : 
                      new Address {
                        Street = a.Street
                        ...
                      }
          };
        }).ToArray()
};

or with the ?? operator

var o = await client.GetOrderAsync(request);
return new Order {
    OrderDate = o.OrderDate,
    ...
    Shipments = o.Shipment_Order?.Select(sh => {
        var s = sh.ReceiverAddress_Shipment;
        var a = s.Address;
        return new Shipment {
            ShipmentID = sh.ShipmentID,
            ...
            Address = s == null ? 
                      null : 
                      new Address {
                          Street = a.Street
                          ...
                      }
        };
    }).ToArray() ?? new Shipment[0]
};
1

If you don't mind violating a few of the extension methods design guidelines, extension methods combined with null-conditional operator ?. can take you reasonably far:

public static class Extensions
{
    public static TOut Map<TIn, TOut>(this TIn value, Func<TIn, TOut> map)
        where TIn : class
        => value == null ? default(TOut) : map(value);

    public static IEnumerable<T> OrEmpty<T>(this IEnumerable<T> items)
        => items ?? Enumerable.Empty<T>();
}

will give you this:

return new Order
{
    OrderDate = o.OrderDate,
    Shipments = o.Shipment_Order.OrEmpty().Select(sh => new Shipment
    {
        ShipmentID = sh.ShipmentID,
        Address = sh.ReceiverAddress_Shipment?.Address.Map(a => new Address
        {
            Street = a.Street
        })
    }).ToArray()
};

and if you mostly need arrays, then override ToArray extension method to encapsulate a few more method calls:

public static TOut[] ToArray<TIn, TOut>(this IEnumerable<TIn> items, Func<TIn, TOut> map)
    => items == null ? new TOut[0] : items.Select(map).ToArray();

resulting in:

return new Order
{
    OrderDate = o.OrderDate,
    Shipments = o.Shipment_Order.ToArray(sh => new Shipment
    {
        ShipmentID = sh.ShipmentID,
        Address = sh.ReceiverAddress_Shipment?.Address.Map(a => new Address
        {
            Street = a.Street
        })
    })
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.