Page 181 - CSharp/C#
P. 181

This also can be used by operators:


         public class Land
         {
             public double Area { get; set; }

             public static Land operator +(Land first, Land second) =>
                 new Land { Area = first.Area + second.Area };
         }





        Limitations



        Expression-bodied function members have some limitations. They can't contain block statements
        and any other statements that contain blocks: if, switch, for, foreach, while, do, try, etc.


        Some if statements can be replaced with ternary operators. Some for and foreach statements can
        be converted to LINQ queries, for example:


         IEnumerable<string> Digits
         {
             get
             {
                 for (int i = 0; i < 10; i++)
                     yield return i.ToString();
             }
         }



         IEnumerable<string> Digits => Enumerable.Range(0, 10).Select(i => i.ToString());


        In all other cases, the old syntax for function members can be used.

        Expression-bodied function members can contain async/await, but it's often redundant:


         async Task<int> Foo() => await Bar();


        Can be replaced with:


         Task<int> Foo() => Bar();


        Exception filters


        Exception filters give developers the ability to add a condition (in the form of a boolean expression)
        to a catch block, allowing the catch to execute only if the condition evaluates to true.


        Exception filters allow the propagation of debug information in the original exception, where as
        using an if statement inside a catch block and re-throwing the exception stops the propagation of
        debug information in the original exception. With exception filters, the exception continues to
        propagate upwards in the call stack unless the condition is met. As a result, exception filters make



        https://riptutorial.com/                                                                             127
   176   177   178   179   180   181   182   183   184   185   186