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.

2 Answers 2

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

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...
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.