'What does '=>' mean (in functions / property context)?
I got an auto generated code using Lambdas while developing a Xamarin application:
public override string this[int position] => throw new NotImplementedException();
public override int Count => throw new NotImplementedException();
What does the => operator mean in this context?
Thanks R
Solution 1:[1]
These are not lambdas, they are Expression-bodied Members!
In the context of a property, these are basically the getters of a property simplified to become a single expression (as opposed to a whole statement).
This:
public override int Count => throw new NotImplementedException();
Is equivalent to:
public override int Count {
get { throw new NotImplementedException(); }
}
Solution 2:[2]
As @sweeper says in your example they do not relate to lambda expressions as they are expression body operators (which were introduced in C# 6 and expanded on in 7). It is also used to indicate a lambda expression though, so it's usage is two fold.
Further information on each usage of the => operator can be found here; https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator
Solution 3:[3]
First, let's clarify that the =>operator is currently used in two different contexts:
Lambda expressions. Often you will see them in Linq, e.g.
var query = Customers.OrderBy(x => x.CompanyName);Expression bodied functions. This is what we have here.
In order to understand what => means, please take a look at the following simple example:
using System;
public class Program
{
public void Main()
{
var obj = new Test();
obj.Count.Dump();
obj[7].Dump();
}
class Test
{
public int Count => 1;
public string this[int position] => $"2 x {position} = {(2*position)}";
}
}
Dumping object(Int32)
1
Dumping object(String)
2 x 7 = 14
Here, the NotImplementedException code, which is just there to tell you (the developer) that the property and indexer is not implemented but should be, is replaced by some function:
- Count is a readonly property returning always 1
- whenever you apply
[ ... ]to the object, the doubled index is returned
Note that in earlier versions of C# you had to write:
class Test
{
public int Count { get { return 1; } }
public string this[int position] {
get { return String.Format("2 x {0} = {1}",
position, (2*position).ToString()); }}
}
which is equivalent to the code above. So in essence in C#7 you have to type much less to achieve the same result.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 |
