How to Write a Lambda Expression in C#
x => x * x is a whole method in one line: it takes x and returns x * x. Lambdas like this go wherever C# expects a method, such as in a Func variable or in a call to Where.
General Programming Concepts and Languages
View All Tagsx => x * x is a whole method in one line: it takes x and returns x * x. Lambdas like this go wherever C# expects a method, such as in a Func variable or in a call to Where.
Action click = () => clicks++; adds 1 to the clicks variable every time click() runs. The lambda doesn't get a copy of clicks: it captures the variable itself.
An underscore, _, tells C# and anyone reading the code that a value isn't needed. int.TryParse("42", out _) checks whether the text is a number without keeping the number.
A method can return a Task without being async: it does its quick checks, then returns the Task another method gave it. Its checks then throw at the call itself, instead of waiting inside the task.
async ValueTask<int> instead of async Task<int> lets a method that usually has its answer at once, such as from a cache, return it without creating a Task object each time. You await it the same way.
FindCapital("Japan")! tells the compiler: this can't be null here. The ! after the call removes the nullable warning, and changes nothing when the program runs.
animal as Dog gives you the animal as a Dog when it is one, and null when it isn't, without an exception. You then check for null before using it.
nickname is null is true when nickname has no value, and city is not null is true when city has one. Unlike == null, these checks can't be changed by the type you're checking.
count++ adds 1 to count. Inside a bigger expression, the place of the ++ decides the value you get: a++ gives the value from before the addition, ++a the value after it.
In a new console app, Program.cs starts straight with code: no namespace, no class Program, no static void Main. These top-level statements are the program, and the compiler wraps them in an entry point method for you.