d1du
d1du

Reputation: 316

c#: how to use "=>" in method with multi line body?

How do I write a method with "=>" that is multi lined?

public int SimpleAddition(int firstInt, int secondInt) => firstInt + secondInt;

If I am not mistaken, the above method is equivalent to:

public int SimpleAddition(int firstInt, int secondInt){
    return firstInt + secondInt;
}

How would I write this method using "=>" if logic spans multiple lines?

public int SimpleAddition(int firstInt, int secondInt){
    //do something else here//
    return firstInt + secondInt;
}

Upvotes: 0

Views: 742

Answers (2)

Mahmoud Mohammad
Mahmoud Mohammad

Reputation: 16

you can use multi-line lambda expression (block lambda) using {}

example

using System;
                
public class Program
{
   // Example of a multi-line lambda expression (block lambda)
   Func<int, int, int> add = (a, b) =>
   {
       int result = a + b;
       return result;
   };
   public static void Main()
   {
       Program p = new Program();
       Console.WriteLine(p.add(5, 5));
   }     
}

the function has 3 'int' here: two are refering to a and b, and the third is to the returned value

Upvotes: 0

Guru Stron
Guru Stron

Reputation: 143098

How would I write this method using "=>" if logic spans multiple lines?

You would not. The following:

public int SimpleAddition(int firstInt, int secondInt) => firstInt + secondInt;

is expression-bodied method and expression-bodied members as the documentation states can consist only from single expression:

Expression body definitions let you provide a member's implementation in a concise, readable form. You can use an expression body definition whenever the logic for any supported member, such as a method or property, consists of a single expression.

Note that several chained method calls for example (like fluent APIs/LINQ) still form a single expression. For example:

public int SimpleAddition(int firstInt, int secondInt) 
    => new[] { firstInt, secondInt } // just for example
        .Where(_ => true) 
        .Sum();

So if you can rewrite your additional code in a way that it can be chained (or form a single expression) then you will be able to rewrite method to be expression-bodied (does not mean that you should though).

Upvotes: 3

Related Questions