Thursday, October 26, 2017

Expression Bodied Functions and Properties in C#

Since C# 6 you can take advantage of using much more laconic expression bodied functions. Oh, expression bodied basically means lambdish or just bodiless :)

using System;

namespace ConsoleApp
{
    class Program
    {
        static void ExpressionBodiedMethod(string str) => Console.WriteLine(str);

        static void Main(string[] args)
        {
            ExpressionBodiedMethod("Hello!");
        }
    }
}

That shortened syntax can also be used to create a getter-only property:

using System;

namespace ConsoleApp
{
    class Program
    {
        static string ExpressionBodiedReadOnlyPrpoperty => "Hello!";
        /*static string ExpressionBodiedReadOnlyPrpoperty { get; } = "Hello!";*/

        static void ExpressionBodiedMethod(string str) => Console.WriteLine(str);

        static void Main(string[] args)
        {
            ExpressionBodiedMethod(ExpressionBodiedReadOnlyPrpoperty);
        }
    }
}

No comments:

Post a Comment