acjialiren
acjialiren

Reputation: 151

About creating a delegate object - C#

I define a Delegate type like :

delegate void DrawShape(Brush aBrush,Rectangle aRect);

Would you tell me why the below below methods of creating delegate object are all correct:

DrawShape DrawRectangleMethod = CreateGraphics().FillRectangle;
DrawShape AnotherDrawRectangleMethod = new DrawShape(CreateGraphics().FillRectangle);

Why can the method without "New" work correctly?

Upvotes: 2

Views: 111

Answers (3)

RobertMS
RobertMS

Reputation: 1155

C# is smart enough to handle method groups for you. A method group is the method name without the parentheses; there may be many overloads of the method with different signatures, but the "base" name without parentheses is called the method group. The compiler will insert the constructor call for you, allowing you to write a more concise line of code.

Upvotes: 1

Oliver
Oliver

Reputation: 45119

Cause the compiler will automatically insert it for you. It's just syntactic sugar.

Simply take a look into Jons Bluffer's Guide at chapter Delegates.

Upvotes: 0

vc 74
vc 74

Reputation: 38179

DrawShape DrawRectangleMethod = CreateGraphics().FillRectangle;

is possible thanks to C#2's implicit method group conversions which are spec'd here.

Upvotes: 3

Related Questions