What is the => operator when not used with a lambda expression? [duplicate]
Asked Answered
C

1

6

I was looking at someone's library the other day and they had this:

internal static string BaseUrl => "https://api.stripe.com/v1";
public static string Invoices => BaseUrl + "/invoices";

Isn't the => just acting like an assignment = operator? Wouldn't this be the same:

internal static string BaseUrl = "https://api.stripe.com/v1";
public static string Invoices = BaseUrl + "/invoices";

Never saw this before.

Chickpea answered 18/4, 2016 at 22:2 Comment(2)
One comment... You're right, the way that library is coded, the assignment operator would be more appropriate. HOWEVER, if the property needed to be dynamically calculated on the fly, you can't just use an assignment operator, e.g. public static string CurrentDateTimeAsString => DateTime.Now.ToString()Roundtree
Thanks. Tried to find it, but didn't know what to call it so nothing turned up.Chickpea
W
7

This is a new feature in C# 6.0 called Expression-Bodied, is a syntactic sugar that allows define getter-only properties and indexers where the body of the getter is given by the expression body.

public static string Invoices => BaseUrl + "/invoices";

Is the same as:

public static string Invoices
{
    get 
    {
        return BaseUrl + "/invoices";
    }
}

You can read more here.

Also you can define methods as well with this syntax:

public void PrintLine(string line) => Console.WriteLine(line);
Weil answered 18/4, 2016 at 22:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.