I'm a bit confused of the usage of the += operator. I understand that it is a compound operator that is used to both add and assign. However I've seen it used in the following manner.

Class objectVar += new Class

what is different about that vs

Class objectVar = new Class

Hopefully that question makes sense.

Thanks in advance.

There are two possible reason. Object have special defination for operation += or class is an event and += operations adds new event handler.

Ah thank you. I just wasn't getting that usage for some reason but you are right it was.

[object].[event] += new EventHandler(anEvent);

It's not that it's an event, it is that it is a delegate. A delegate is a pointer to other methods. A delegate can point to an unlimited amount of methods and when you call a delegate you call all its appointed methods.

Its used so at compile time the method doesn't need yet to know which methods need to be invoked. and is assigned always via a "+=" operator.

It's also worth noting that you can use the -= operator to stop the delegate pointing to a method e.g.

Car myCar = new Car();

public void Start()
{
    myCar.Crash += new Car.CrashEventHandler(myMethod);
}

private void myMethod()
{
   ...
}

public void Stop()
{
    myCar.Crash -= new Car.CrashEventHandler(myMethod);
}
commented: Indeed! +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.