7

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?

J. Doe
  • 905
  • 1
  • 10
  • 23

4 Answers4

9

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;
    }
}
David
  • 10,458
  • 1
  • 28
  • 40
5

Take a look at this Microsoft Article. It's a C# 6.0 feature where properties have no statement body. You could use them to get methods, or single line expressions. For example:

public override string ToString() => string.Format("{0}, {1}", First, Second);
Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69
4

A new feature in C# 6.0 called an expression body.

It is shorthand to write a single line of code with a return value.

For example

int GetNumber() => 1;

Is an expression body statement which is the same as:

int GetNumber()
{
    return 1;
}

You can read more here

plusheen
  • 1,128
  • 1
  • 8
  • 23
1

It's a new shorthand syntax in C# 6.

In your first example it's defining a public method, Calculate(int x) whose implementation is defined within DoSomething(x).

An equivalent definition would be:

class SomeClass {

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

    protected int DoSomething(int x) { ... }
}
STW
  • 44,917
  • 17
  • 105
  • 161