Expression – Bodied Methods in C# 6.0

By | December 5, 2014

Expression-bodied methods is another feature in C# 6.0  that simply the syntactic expression in C# . We are already familiar with  Lambda expression  that associate with function and  call by a delegation.  Expression-bodied members extend the similar use of lambda expressions for methods.

Following code block show, we have a GetTime() method that returns a formatted time and application prints it in console. This is what we do typically till now.

class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetTime());
}
public static string GetTime()
{
return "Current Time - " + DateTime.Now.ToString("hh:mm:ss");
}
}

With the use of C# 6.0, Expression Bodied Methods, we can use the Lambda expression for the method definition part.

class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetTime());
}
public static string GetTime() =>   "Current Time - " + DateTime.Now.ToString("hh:mm:ss");
}

isn’t a cool features ?  and this also makes our code clean and clear to understand.

Must Read :  What’s new in C# 6.0 ?

One thought on “Expression – Bodied Methods in C# 6.0

Comments are closed.