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
Try it in DotNetFiddle
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.