简体   繁体   中英

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

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(); }
}

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://learn.microsoft.com/en-us/do.net/csharp/language-reference/operators/lambda-operator

First, let's clarify that the => operator is currently used in two different contexts:

  1. Lambda expressions. Often you will see them in Linq, eg
    var query = Customers.OrderBy(x => x.CompanyName);

  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM