Loading...

C# Lambda

Add a function with no name under the two lines you already print, and use it to join them. Hold<string> still prints pine. Hold<int> still prints 12. A lambda then prints pine x12 on a third line. dotnet run shows those three lines.
Optional Advanced continues, so Pine, Hold<T>, and Item stay. The generics page stopped at the two lines. This page keeps that pair and adds one call. If you only see pine and 12, the lambda is missing, it is never called, or dotnet run --no-build is still running the generics program. dotnet run compiles first. Use that command for the check.

A function stored in a variable

Open the PineLab project. Keep Hold<T>, the field Item, and the constructor. Keep Main() with empty parentheses. Keep the two holders:
Hold<string> word = new Hold<string>("pine");
Hold<int> number = new Hold<int>(12);
Under them, store a lambda. Func is in System, and the file already has using System;. You do not add a namespace.
Func<string, int, string> label = (name, count) => name + " x" + count;
Read the type from the left. The last type argument is the result, a string. The ones before it are the inputs: a string, then an int. label is camelCase, a local, like word. The => splits the parameters from the body. The body is one expression. It has no semicolon of its own and no return. The space before x sits inside the quotes, the same join the old label method used, now without a method name.
Then print the two fields and the call, in that order:
Console.WriteLine(word.Item);
Console.WriteLine(number.Item);
Console.WriteLine(label(word.Item, number.Item));
Pass word.Item and number.Item, not the holders. word is a Hold<string>. The lambda wants a string.

Hold plus a lambda that joins the two values

csharp
using System;

public class Hold<T>
{
    public T Item;

    public Hold(T item)
    {
        Item = item;
    }
}

public class Pine
{
    public static void Main()
    {
        Hold<string> word = new Hold<string>("pine");
        Hold<int> number = new Hold<int>(12);
        Func<string, int, string> label = (name, count) => name + " x" + count;
        Console.WriteLine(word.Item);
        Console.WriteLine(number.Item);
        Console.WriteLine(label(word.Item, number.Item));
    }
}

Three lines

From PineLab, run dotnet run. The screen shows pine, then 12, then pine x12.
Walk Main once. It builds the string holder and the int holder. It stores the lambda in label and does not run it yet. The first WriteLine prints Item on the string holder. The second prints Item on the int holder. The third calls label with those two values. The expression joins them, and WriteLine prints the string it returns. Hold does not change. Item is still pine and still 12 after the call.
Drop the space in " x" and the third line is pinex12. Put the space back. The first two lines do not show the space problem. Only the lambda's line does.
There is no fourth line. No date. No args. A word after -- is ignored, because Main() takes no parameters. The pine on the screen is the constructor argument, then the same letters again inside the lambda's result.

The arrow does not run itself

The line with => stores a function. It prints nothing. If you delete Console.WriteLine(label(word.Item, number.Item)); and leave the Func line, the build succeeds and the screen is the generics screen again: pine, then 12. The lambda is in the file and never starts. Put the call back.
The call is what runs the body. Each call runs it again. A second call with the same arguments prints pine x12 again. This file calls it once.
A lambda with a block needs more syntax. (name, count) => { return name + " x" + count; } is legal: braces, return, and a semicolon inside the block. The checked file does not use that form. It uses the single expression, with no braces and no return. If you add braces and forget return, the build fails and none of the three lines appear.
Action<string> is the cousin that returns nothing. This page does not use it. Func is the one that returns the third line.

Two parameters need parentheses

One parameter may skip the parentheses: Func<int, int> twice = n => n + n; is legal. twice(12) would return 24. That shape is not in the file you keep. A fourth line 24 means you left that call in. Delete it before you judge the three lines.
Two parameters do not get that shortcut. (name, count) needs the parentheses. name, count => name + " x" + count does not compile. The comma is not a legal start of a lambda. Put the parentheses back.
Zero parameters also need parentheses: () => "pine". You do not need that form here. The checked lambda takes the word and the number so the third line follows the holders.
The types on Func decide the parameter types. You do not write string and int again in front of name and count. You may: (string name, int count) => name + " x" + count also compiles. The file you keep leaves the types on Func only.

A bad call fails the build

label(word, number) passes two holders. The lambda wants a string and an int. The build stops, and you do not get the three lines. Pass .Item on each.
label(word.Item, word.Item) passes two strings. The second parameter is an int. The build stops the same way. The lambda does not turn the second pine into a number.
label(number.Item, word.Item) swaps them. An int is not a string, so the build stops. Order follows Func<string, int, string>: string first, int second, string out.
None of these failures are runtime stops after pine has printed. They are compile errors. Main does not start. Fix the call, then dotnet run again.
The lambda does not replace Hold. You still need the class to store pine and 12. A file with only the Func and two literals would print one line, pine x12, and would drop the two lines this module is keeping. Keep the holders.

LINQ stays shut

You can keep pine and 12 on their own lines and add pine x12 from a function that has no name. The next page is LINQ. It asks questions of a list, with words such as Where. This page stops before that. There is no list in this file, no Where, and no Select. The lambda here is one variable you call yourself.
One last pass: Hold<T> unchanged, Main() with no arguments, one Func<string, int, string>, the body name + " x" + count, one call with both .Item values, no extra twice, you are in PineLab, and dotnet run shows pine, then 12, then pine x12. When those three lines match, the lambda did its job.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
5
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top