Delegate/Event HELL!

S

Scott M.

I need a little help please...

I'm simply trying to set up a very basic event for a class and then create
an event handler for that class in a Console application.

I think I'm very close, but I'm missing something. Here's what I've got...

//Abbreviated class code
using System;
namespace foo
{
public class fooFoo
{
public delegate void myEventEventHandler();
public event myEventEventHandler myEvent;

public void ChangeSpeed(short ByHowMuch)
{
if (test that determines if the event should be raised)
{
myEvent();
}
}
}
}
// *************************************************

//Console application that has reference to above class's assembly...
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using foo;

namespace TestClass
{
internal sealed class Module1
{
// >--- An "Aside" question here ---<
//Why does the compiler force me to declare the following instance
as static?
//Is it because the class is "internal sealed"?
static fooFoo x = new fooFoo();

public static void Main()
{
//The following line is what won't compile...
//I get the following error message:
//Cannot implicitly convert type 'System.EventHandler' to
'foo.fooFoo.myEventEventHandler'
x.myEvent += new System.EventHandler(x_myEvent);
}

private static void x_myEvent(object sender, System.EventArgs e)
{
Console.WriteLine("");
}
}
}

Thanks for your help!
 
P

Peter Duniho

Scott M. said:
I need a little help please...

I'm simply trying to set up a very basic event for a class and then create
an event handler for that class in a Console application.

I think I'm very close, but I'm missing something. Here's what I've
got...


I think "hell" is overstating things a bit. :)

Your main problem is simply that you are creating the wrong kind of event
handler. That's exactly what the error message is telling you.

Use "new fooFoo.myEventEventHandler(x_myEvent)" instead.

Of course, when you do you will find that you've declared the delegate
incorrectly, leaving out the parameters that you want passed. But that's a
different bug. :)

As far as why the compiler requires the x member to be declared static, I
believe it's because your class is implicitly static. That is, you didn't
declare the class as static, but it has no non-static members, and no public
constructor.

If you want the class to be instanced, I'd guess adding a public constructor
that does nothing would address that issue.

Pete
 
S

Scott M.

Thanks Peter! Yes, it has been hell, since I am coming from VB.NET where,
we don't have to deal with this at all to get an event up and running! It's
working now though.

Thanks.
 

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

Top