Description
This article describes a new feature of C# 6.0 using Visual Studio Ultimate 2015 Preview.
Content
As we all know Microsoft has launched a new version of C# called C# 6.0 with Visual Studio Ultimate 2015 Preview and there is a new feature in C# 6.0 based on "Expression bodies of function members".
Sometimes we create small functions with 1 or 2 lines to do some task or activities like conversion or printing. So in C# 6.0 this feature allows us to optimize that function with a “Lamda Expression” like:
- public int FunctionName() => 0;
We can use methods, properties and other kinds of function members to have bodies that are expressions instead of statement blocks, just like with lambda expressions.
Let's see this feature.
I am using Visual Studio Ultimate 2015 Preview.
Open Visual Studio 2015 and select "File" -> "New" -> "Project" and fill in the project name such as "Console Application1".
After creating the project, I will access some common static methods in "program.cs" without using a class name every time.
Example 1
In this example, I will write a method that will print the string value.
Code
- class Program
- {
- static void Main(string[] args)
- {
-
- PrintString("Welcome To C# Corner");
- Console.ReadKey();
-
- }
- public static void PrintString(string str)
- {
- Console.WriteLine(str);
- }
- }
It will give the output:
But in C# 6.0 we can optimize this method definition with a "Lamda Expression" in a single line.
- class Program
- {
- static void Main(string[] args)
- {
-
- PrintString("Welcome To C# Corner");
- Console.ReadKey();
-
- }
-
- public static void PrintString(string str) => Console.WriteLine(str);
-
- }
Output
Example 2
In this example, I will write a method that will get 2 integer values and provide the product of them as a result.
Code
- class Program
- {
- static void Main(string[] args)
- {
-
- Console.WriteLine(multiply(2, 3).ToString());
- Console.ReadKey();
-
- }
- public static int multiply(int var1, int var2)
- {
- return (var1 * var2);
- }
- }
It will give the output:
But in C# 6.0 we can optimize this method definition with a "Lamda Expression" in a single line.
- class Program
- {
- static void Main(string[] args)
- {
-
- Console.WriteLine(multiply(2, 3).ToString());
- Console.ReadKey();
-
- }
- public static int multiply(int var1, int var2) => (var1 * var2);
- }
Output
Conclusion
Now you have understood the new feature of C# 6.0 that allows the use of "Expression bodies of function members".