The One New Improvement of C# 10 Drastically Simplifies Lambda Functions
Type inference got enabled for lambda expressions
--
Microsoft has given Lambdas a kind of superpower with the latest version of C#. That new strength leads to more compact and easier-to-understand code.
Explicit-type conversions are frequently no longer necessary. Read the C# language reference, and you will find the information that the lambda expression is used to create an anonymous function. The lambda expression can be formulated with a simple expression:
(input) => expression
Or it is in the form of an instruction lambda with an instruction block:
(input) => { statement/s }
Direct Comparison: The Old Fashioned Way
I will show you the new language feature by creating a direct comparison.
This seems to be the best way to demonstrate the new features of C#10. You will be able to draw a direct comparison between before and but that's how it works now the example below:
This code calculates the area of a square given by the user's input from the console window (compare figure 1).
Line 6 defines the delegate execute
. Its body is more extensive and will be examined in more detail later.
All you need to know by now is that it accepts another delegate and returns the generic data type object
. The return type can vary in the body, controlled by case distinctions. But more about this later.
Lines 9 to 11 call the execute
delegate three times.
- The first call is a lambda expression (line 9).
- The other call (line 10) uses a method group.
- The call in line 11 also uses a method group with the double type instead of an integer value as input and return type.