How to Create Custom Events?

  • Thread starter Thread starter jp2msft
  • Start date Start date
J

jp2msft

I know how to use events, but how can I create a custom event?

Take the pointless class below:

class MyInt
{
int n;
public MyInt(int value)
{
n = value;
}
}

How would I create an event for it so that I can call a catching method
whenever the value is changed?
 
Great!

Now, on to how to make it impliment easily:

I see your code (sticking with the N property you used and I neglected to
include) would result in something like this:

MyInt Count = new MyInt(0);
// and alter to use it....
Count.N = Count.N + intNewValue;

Could the class be modified so that the workings of it are more transparent
(i.e. more like an 'int' or whatever value I am trying to mimic)?

Example:
MyInt Count = 0;
Count += intNewValue;

This is some cool theory stuff that typically is difficult to find.
 
Beautiful! I'm writing all this down in an email that I'm forwarding to
myself for safe keeping.

I can't wait to start messing around with this new trick.

Thanks, Mr. Duniho!

Peter Duniho said:
[...]
Could the class be modified so that the workings of it are more
transparent
(i.e. more like an 'int' or whatever value I am trying to mimic)?

Example:
MyInt Count = 0;
Count += intNewValue;

Sure. You can overload the + operator for the class, to allow instances
of the class to be added to each other, as well as to provide for adding
an int to your class.

That said, I'll warn that things may start to get confusing if you do
this. Operator overloads can work very nicely for value types, but for a
mutable class, having a binary operator (for example) modify one of the
operands can result in some very non-intuitive code.

In particular, you can't overload +=. You have to overload +, and then
the compiler uses that overload when implementing +=. That means that if
this:

MyInt Count = new MyInt(0); // no overload of assignment operator
Count += intNewValue;

did what you expected, then this:

MyInt Count = new MyInt(0);
MyInt Other = Count + intNewValue;

might not do what you expect ("Other" would wind up referencing the same
instance as "Count", and that single instance of MyInt would have been
modified).

That's because the overload would have to look like this:

public static MyInt operator +(MyInt op1, int op2)
{
op1.N += op2;
return op1;
}

Now, all that said, you could write this:

MyInt Count = new MyInt(0); // no overload of assignment operator
Count.N += intNewValue;

without doing any operator overloading. That's almost as concise as your
desired syntax, but preserves the normal semantics for a mutable reference
type.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top