Lambda expression with a void input

15,965

Solution 1

The nullary lambda equivalent would be () => 2.

Solution 2

That would be:

() => 2

Example usage:

var list = new List<int>(Enumerable.Range(0, 10));
Func<int> x = () => 2;
list.ForEach(i => Console.WriteLine(x() * i));

As requested in the comments, here's a breakdown of the above sample...

// initialize a list of integers. Enumerable.Range returns 0-9,
// which is passed to the overloaded List constructor that accepts
// an IEnumerable<T>
var list = new List<int>(Enumerable.Range(0, 10));

// initialize an expression lambda that returns 2
Func<int> x = () => 2;

// using the List.ForEach method, iterate over the integers to write something
// to the console.
// Execute the expression lambda by calling x() (which returns 2)
// and multiply the result by the current integer
list.ForEach(i => Console.WriteLine(x() * i));

// Result: 0,2,4,6,8,10,12,14,16,18

Solution 3

You can just use () if you have no parameters.

() => 2;

Solution 4

The lmabda is:

() => 2
Share:
15,965
Luk
Author by

Luk

I mostly play with the .Net platform, but I like to test all sorts of stuff.

Updated on June 06, 2022

Comments

  • Luk
    Luk almost 2 years

    Ok, very silly question.

    x => x * 2
    

    is a lambda representing the same thing as a delegate for

    int Foo(x) { return x * 2; }
    

    But what is the lambda equivalent of

    int Bar() { return 2; }
    

    ??

    Thanks a lot!

  • Luk
    Luk over 14 years
    Damn, that was fast :) Thanks everyone!
  • PussInBoots
    PussInBoots almost 11 years
    Hi, this seems like a great example; can you explain it in plain english line by line, piece by piece? :)
  • Ahmad Mageed
    Ahmad Mageed almost 11 years
    @PussInBoots added some comments. Hope that helps!
  • PussInBoots
    PussInBoots almost 11 years
    Thanks. Still a bit puzzled by Func<int> x and x().. I think I need to read up a little bit more on Func, delegates and lambdas..
  • deetz
    deetz over 5 years
    Could someone explain to me, what would be the advantage of this in comparison to just using an constant?