C# 6.0 Feature: Expression bodied methods and proprties

 Expression bodied methods and properties


You can write functions and properties using lambada expressions.By using lambada expression => and after that write code as you usually write into function/property body.

Before C#6

using System;


namespace OldInCSharp6
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            double x = 1.618;
            double y = 3.142;

            Console.WriteLine("Addition:" + AddNumbers(x, y));
            Console.WriteLine("Substraction:"+ SubtractNumbers(x, y));
            Console.WriteLine("Multiplication:"+ MultiplyNumbers(x, y));

            Console.ReadLine();
        }

        /* functions */
        private static double AddNumbers(double x, double y)
        {
            return x + y;
        }
         
        private static double SubtractNumbers(double x, double y)
        {
          return x - y;
        }
        private static double MultiplyNumbers(double x, double y)
        {
            return x* y;
        }

    }

}







In C#6

//Expression bodied function

using static System.Console;

namespace NewInCSharp6
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            double x = 1.618;
            double y = 3.142;

            WriteLine("Addition:" + AddNumbers(x, y));
            WriteLine("Substraction:"+ SubtractNumbers(x, y));
            WriteLine("Multiplication:"+ MultiplyNumbers(x, y));

            ReadLine();
        }

        /* Expression bodied function */
        private static double AddNumbers(double x, double y) => x + y;
        private static double SubtractNumbers(double x, double y) => x - y;
        private static double MultiplyNumbers(double x, double y) => x * y;


    }

}







































// Expression bodied property



using static System.Console;

namespace NewInCSharp6
{
    class Program
    {
        private static void Main(string[] args)
        {
            Myself person = new Myself();
         
            WriteLine("Myself " + person.FullName);
            ReadLine();
        }

        public class Myself
        {
            public string FirstName { get; } = "kamal";
            public string LastName { get; } = "Das";

            /* Expression bodied computed property */
            public string FullName => FirstName + " " + LastName;
        }
    }
}

















C# 6.0 Feature: Expression bodied methods and proprties C# 6.0 Feature: Expression bodied methods and proprties Reviewed by kamal kumar das on November 28, 2016 Rating: 5

No comments:

ads 728x90 B
Powered by Blogger.