C# => Operator

What does = operator mean in a property in C#?

This is an expression-bodied property, a new syntax for computed properties introduced in C# 6, which lets you create computed properties in the same way as you would create a lambda expression. This syntax is equivalent to

public bool property {
get {
return method();
}
}

Similar syntax works for methods, too:

public int TwoTimes(int number) => 2 * number;

What does the = operator mean in a property or method?

What you're looking at is an expression-bodied member not a lambda expression.

When the compiler encounters an expression-bodied property member, it essentially converts it to a getter like this:

public int MaxHealth
{
get
{
return Memory[Address].IsValid ? Memory[Address].Read<int>(Offs.Life.MaxHp) : 0;
}
}

(You can verify this for yourself by pumping the code into a tool called TryRoslyn.)

Expression-bodied members - like most C# 6 features - are just syntactic sugar. This means that they don’t provide functionality that couldn't otherwise be achieved through existing features. Instead, these new features allow a more expressive and succinct syntax to be used

As you can see, expression-bodied members have a handful of shortcuts that make property members more compact:

  • There is no need to use a return statement because the compiler can infer that you want to return the result of the expression
  • There is no need to create a statement block because the body is only one expression
  • There is no need to use the get keyword because it is implied by the use of the expression-bodied member syntax.

I have made the final point bold because it is relevant to your actual question, which I will answer now.

The difference between...

// expression-bodied member property
public int MaxHealth => x ? y:z;

And...

// field with field initializer
public int MaxHealth = x ? y:z;

Is the same as the difference between...

public int MaxHealth
{
get
{
return x ? y:z;
}
}

And...

public int MaxHealth = x ? y:z;

Which - if you understand properties - should be obvious.

Just to be clear, though: the first listing is a property with a getter under the hood that will be called each time you access it. The second listing is is a field with a field initializer, whose expression is only evaluated once, when the type is instantiated.

This difference in syntax is actually quite subtle and can lead to a "gotcha" which is described by Bill Wagner in a post entitled "A C# 6 gotcha: Initialization vs. Expression Bodied Members".

While expression-bodied members are lambda expression-like, they are not lambda expressions. The fundamental difference is that a lambda expression results in either a delegate instance or an expression tree. Expression-bodied members are just a directive to the compiler to generate a property behind the scenes. The similarity (more or less) starts and end with the arrow (=>).

I'll also add that expression-bodied members are not limited to property members. They work on all these members:

  • Properties
  • Indexers
  • Methods
  • Operators

Added in C# 7.0

  • Constructors
  • Finalizers

However, they do not work on these members:

  • Nested Types
  • Events
  • Fields

What does the '=' syntax in C# mean?

It's the lambda operator.

From C# 3 to C# 5, this was only used for lambda expressions. These are basically a shorter form of the anonymous methods introduced in C# 2, but can also be converted into expression trees.

As an example:

Func<Person, string> nameProjection = p => p.Name;

is equivalent to:

Func<Person, string> nameProjection = delegate (Person p) { return p.Name; };

In both cases you're creating a delegate with a Person parameter, returning that person's name (as a string).

In C# 6 the same syntax is used for expression-bodied members, e.g.

// Expression-bodied property
public int IsValid => name != null && id != -1;

// Expression-bodied method
public int GetHashCode() => id.GetHashCode();

See also:

  • What's the difference between anonymous methods (C# 2.0) and lambda expressions (C# 3.0)
  • What is a Lambda?
  • C# Lambda expression, why should I use this?

(And indeed many similar questions - try the lambda and lambda-expressions tags.)

What does = operator pointing from field or a method mean? C#

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;
}
}

+= operator for Delegate

It's not an operator on the delegate type itself, in IL terms - it's defined in the language specification, but you wouldn't find it using reflection. The compiler turns it into a call to Delegate.Combine. The reverse operation, using - or -=, uses Delegate.Remove.

At least, that's how it's implemented when C# targets .NET, as it almost always does. In theory, this is environment-specific - the language specification doesn't require that a compiler uses Delegate.Combine or Delegate.Remove, and a different environment may not have those methods.

From the C# 5 specification, section 7.8.4 (addition):

The binary + operator performs delegate combination when both operands are of some delegate type D. (If the operands have different delegate types, a binding-time error occurs.) If the first operand is null, the result of the operation is the value of the second operand (even if that is also null). Otherwise, if the second operand is null, then the result of the operation is the value of the first operand. Otherwise, the result of the operation is a new delegate instance that, when invoked, invokes the first operand and then invokes the second operand. For examples of delegate combination, see §7.8.5 and §15.4. Since System.Delegate is not a delegate type, operator + is not defined for it.

What does the operator '=' mean in C#?

Basically it's specifying an anonymous function, that takes no parameters that calls SomeAction. So yes, they are functionally equivalent. Though not equal. Using the lambda is more equivalent to:

del = new SomeDelegate(this.CallSomeAction);

where CallSomeAction is defined as:

public void CallSomeAction()
{
this.SomeAction();
}

Hope that helps!

What does question mark and dot operator ?. mean in C# 6.0?

It's the null conditional operator. It basically means:

"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."

In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.

In other words, it's like this:

string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
...
}

... except that a is only evaluated once.

Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:

FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null

What does the '%' operator mean?

It is the modulo (or modulus) operator:

The modulus operator (%) computes the remainder after dividing its first operand by its second.

For example:

class Program
{
static void Main()
{
Console.WriteLine(5 % 2); // int
Console.WriteLine(-5 % 2); // int
Console.WriteLine(5.0 % 2.2); // double
Console.WriteLine(5.0m % 2.2m); // decimal
Console.WriteLine(-5.2 % 2.0); // double
}
}

Sample output:

1
-1
0.6
0.6
-1.2

Note that the result of the % operator is equal to x – (x / y) * y and that if y is zero, a DivideByZeroException is thrown.

If x and y are non-integer values x % y is computed as x – n * y, where n is the largest possible integer that is less than or equal to x / y (more details in the C# 4.0 Specification in section 7.8.3 Remainder operator).

For further details and examples you might want to have a look at the corresponding Wikipedia article:

Modulo operation (on Wikipedia)

Meaning of () = Operator in C#, if it exists

This introduces a lambda function (anonymous delegate) with no parameters, it's equivalent to and basically short-hand for:

delegate void () { return action.GenerateDescription(); }

You can also add parameters, so:

(a, b) => a + b

This is roughly equivalent to:

delegate int (int a, int b) { return a + b; }


Related Topics



Leave a reply



Submit