Reputation: 65308
I have seen this code in NodaTime. Here is the code here
public bool Equals(DateInterval other) => this == other;
This code uses the =>
operator to define the body of a function. I tried to create a project using syntax but keeps giving me an error. I am using visual studio 2012. How can I use this same syntax in my code.
Upvotes: 1
Views: 99
Reputation: 4630
Expression-bodied function members allow properties, methods, operators and other function members to have bodies as lambda like expressions instead of statement blocks. Thus reducing lines of codes and clear view of the expressions.
Now in C# 6.0, instead of writing the whole property body using getters/setters, you can now just use the lambda arrow (“=>”) to return values.
For example, the below code returns the string “My Name” when you access the property “NewName”. Remember that, in this case you don’t have to write the “return” keyword. The lambda arrow (=>) will do the same for you internally.
Public string NewName=>"My Name" //this is the new way
public string NewName//this was the old
{
get
{
return "My Name";
}
}
Another Example
Public int NewSum(int a,int b)=>a+b;//new way
public int oldSum(int a,int b)//old way
{
return a+b;
}
Upvotes: 1
Reputation: 2612
public bool Equals(DateInterval other) => this == other;
is equivalent to:
public bool Equals(DateInterval other)
{
return this==other;
}
Upvotes: 2
Reputation: 138241
This is an expression-bodied function from C# 6. It's supported in Visual Studio 2015 and above. You can read more on the announcement of C# 6 (look for "Expression Bodied Functions and Properties").
Upvotes: 6