Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 815
Bill Noel Avatar asked Apr 18 '16 22:04

Bill Noel


People also ask

What is the use of => in C#?

The => token is supported in two forms: as the lambda operator and as a separator of a member name and the member implementation in an expression body definition.

Which sentence about lambda statement is not true?

Which is NOT true about lambda statements? A statement lambda cannot return a value.

What is the type of a lambda expression?

The lambda expressions have a very simple, precise syntax and provide flexibility to specify the datatypes for the function parameters. Its return type is a parameter -> expression body to understand the syntax, we can divide it into three parts.

Can we write a Parameterless lambda expression?

Lambda expressions can be parameterless or have one or more parameters. The following code snippet illustrates a lambda expression that doesn't have any parameters. () => Console. WriteLine("This is a lambda expression without any parameter");


1 Answers

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);
like image 136
Arturo Menchaca Avatar answered Oct 15 '22 11:10

Arturo Menchaca