3

I am trying to understand the excel add in programming using C#. For such a project there is a file called ThisAddIn.cs which handles all the events like WorkBookOpen, WorkBookClose, etc. The code to handle such an event is something like this -

this.Application.WorkbookOpen += new Excel.AppEvents_WorkbookOpenEventHandler(Application_WorkbookOpen);

This looks straightforward in terms of what it is doing but I am not understanding why is it using the += sign for assignment instead of just = symbol. What does the += symbol signify in this type of assignment. Is it something related to C# or specific to AddIn development. I am also very new to C#. Any help would be appreciated.

Thanks.

ravi
  • 1,707
  • 4
  • 29
  • 44

2 Answers2

12

This is one of the stranger conventions in C#. The things to know are:

  • A delegate is an object that represents the ability to invoke one or more methods.
  • The sum of two delegates is a third which when invoked, invokes its summands.
  • When an event occurs, the delegate associated with that event is invoked.

So for example, if you have:

static void M() { Console.WriteLine("Hello!"); }
static void N() { Console.WriteLine("Goodbye!"); }
...
Action foo = M;
foo(); // Hello!
Action bar = N;
bar(); // Goodbye!
Action sum = foo + bar;
sum(); // Hello! Goodbye!
foo += bar; // Same as foo = foo + bar
foo(); // Hello! Goodbye!

Now is it clear why += means "associate this handler with the event"?

(And incidentally, I wrote a lot of the Excel C# add-in code, back in the day.)

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • I have been programming in C# for 8 years and I never knew this went beyond the syntax sugar for "hook up an event handler." I swear I discover some new corner of this language every week... – user1454265 May 07 '15 at 14:42
3

The += is a C# convention used to add an event handler. That code there means that you're hooking up the Application_WorkbookOpen function to the WorkbookOpenEvent.

http://msdn.microsoft.com/en-us/library/ms743596.aspx

Joe Korolewicz
  • 474
  • 4
  • 21