Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences in assigning C# event handlers?

I've always assigned event handlers like this, guided by Intellisense auto-completion.

RangeSelector.RangeChanged += new EventHandler(RangeSelector_RangeChanged);

I've recently noticed one of my colleagues does it this way.

RangeSelector.RangeChanged += RangeSelector_RangeChanged;

Both methods are syntactically correct, compile and behave as expected.

What are the differences, benefits or disadvantages of these methods. Do they result in the same IL code or is there some subtle difference that I need to be aware of?

like image 896
Steve Crane Avatar asked Aug 25 '09 08:08

Steve Crane


People also ask

What are the different assignment operators explain?

There are two kinds of assignment operations: simple assignment, in which the value of the second operand is stored in the object specified by the first operand. compound assignment, in which an arithmetic, shift, or bitwise operation is performed before storing the result.

Is += different from =+ in C?

In modern C, or even moderately ancient C, += is a compound assignment operator, and =+ is parsed as two separate tokens. = and + . Punctuation tokens are allowed to be adjacent.

How are values assigned in C?

Assigning values to C and C++ variables To assign a value to a C and C++ variable, you use an assignment expression. Assignment expressions assign a value to the left operand. The left operand must be a modifiable lvalue. An lvalue is an expression representing a data object that can be examined and altered.

How do you tell the difference between the equal to and assignment operators?

What is the difference between = (Assignment) and == (Equal to) operators. The “=” is an assignment operator is used to assign the value on the right to the variable on the left. The '==' operator checks whether the two given operands are equal or not. If so, it returns true.


2 Answers

What are the differences, benefits or disadvantages of these methods.

The second method is newer, i.e. it is only supported since C# 2.0 (I believe), which added an automatic conversion from a method group (i.e. a method name) to a delegate. The constructor call is thus added by the compiler and the second method is just syntactic sugar for the first one.

Because of that, there are no other differences between the two.

Since the second method does the same as the first, with less syntax, it should be preferred.

like image 190
Konrad Rudolph Avatar answered Nov 06 '22 20:11

Konrad Rudolph


No difference, it results in the same IL.

It's just a way to say the same thing with less code.

like image 3
Nifle Avatar answered Nov 06 '22 21:11

Nifle