๐Ÿ˜œ

์ญˆ๋‚˜์•„๋น  ๋ธ”๋กœ๊ทธ

JUNA
STUDIO

[C#] Improvements to Lambda Expressions in C# 10

๋ฐœํ–‰์ผ: Jan, 2025
์กฐํšŒ์ˆ˜: 3
๋‹จ์–ด์ˆ˜: 280

Table of Contents

Introduction

 .NET 6 supports C# language version 10. Among various improvements, there have been some enhancements to lambda expressions. Let's take a look.

Original link: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions#explicit-return-type


1. Natural Type of a Lambda Expression

 In the past, assigning a lambda expression to a variable with a var type would result in an error, requiring explicit type declaration with Func<string, int>. Now, the compiler is smart enough to infer the return type from the lambda expression.

var parse = (string s) => int.Parse(s);

This should have been possible a long time ago... It seems like Microsoft is not working hard enough.


2. Explicit Return Type of a Lambda Expression

In the following lambda expression, the return type is ambiguous because it returns an int or a string based on the value of b, causing a compiler error. This often happens when multiple types need to be returned, and explicitly casting the return type can be cumbersome.

var choose = (bool b) => b ? 1 : "two"; // ERROR: Can't infer return type

Starting with C# 10, you can explicitly specify the return type in front of the lambda expression.

var choose = object (bool b) => b ? 1 : "two"; // Func<bool, object>

Personally, I wish the compiler would implicitly interpret such cases as object type without needing to explicitly write object. Sometimes C# feels a bit frustrating compared to other languages, but I hope many improvements will be made soon.


3. Attributes

 You can now specify attributes for lambda expressions or their parameters. Personally, I have never felt the need to specify attributes for lambda expressions, but it's always good to have more flexibility...

 You can specify attributes for lambda expressions as shown below:

Func<string?, int?> parse = [ProvidesNullCheck] (s) => (s is not null) ? int.Parse(s) : null;

 You can also specify attributes for each parameter or for the return value as shown below: 

var concat = ([DisallowNull] string a, [DisallowNull] string b) => a + b;
var inc = [return: NotNullifNotNull(nameof(s))] (int? s) => s.HasValue ? s++ : null;

Tags: #.NET 6#C# 10#lambda expressions#compiler#attributes
JUNA BLOG VISITORS
Today
1
 (
updown
-6
)
Total
62
 (
updown
+1
)

ยฉ 2025 juniyunapapa@gmail.com.