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.

Bill Noel
  • 1,120
  • 9
  • 21
  • 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()* – Colin Apr 18 '16 at 22:13
  • Thanks. Tried to find it, but didn't know what to call it so nothing turned up. – Bill Noel Apr 20 '16 at 12:06

1 Answers1

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);
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53