Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does => operator pointing from field or a method mean? C# [duplicate]

I've seen an operator => used in the following example:

public int Calculate(int x) => DoSomething(x);

or

public void DoSoething() => SomeOtherMethod();

I have never seen this operator used like this before except in lamba expressions.

What does the following do? Where, when should this be used?

like image 634
J. Doe Avatar asked Sep 12 '16 15:09

J. Doe


People also ask

What is the => operator in C#?

=> used in property is an expression body . Basically a shorter and cleaner way to write a property with only getter . public bool MyProperty => myMethod(); It's much more simpler and readable but you can only use this operator from C# 6 and here you will find specific documentation about expression body.

What does => mean in Linq?

The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation.

Which operator Cannot be applied to a pointer of type void?

c# - Operator '/' cannot be applied to operands of type 'void' and 'void' - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.

Can we create a method inside a method in C#?

Creating a method inside another method is called local functions in C#. Using a method inside another method makes code easier to read. Local functions is just like lamda expressions. Local function is a private method.


1 Answers

These are Expression Body statements, introduced with C# 6. The point is using lambda-like syntax to single-line simple properties and methods. The above statements expand thusly;

public int Calculate(int x)
{
    return DoSomething(x);
}

public void DoSoething()
{
    SomeOtherMethod();
}

Notably, properties also accept expression bodies in order to create simple get-only properties:

public int Random => 5;

Is equivalent to

public int Random
{
    get
    {
        return 5;
    }
}
like image 107
David Avatar answered Sep 23 '22 18:09

David