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?
=> 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.
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.
c# - Operator '/' cannot be applied to operands of type 'void' and 'void' - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With