Dmitry Makovetskiyd
Dmitry Makovetskiyd

Reputation: 7053

i have an error when creating an event

i have the following:

a game class

class Game
{
    public event EventHandler GameOver;

    public void go()
    {
        PlayerAliveEventArgs playerAlive = new PlayerAliveEventArgs(Alive);
        GameOver(this, playerAlive);
    }
}

then i have a class

public  class PlayerAliveEventArgs : EventArgs
{
    public bool Alive { get; set; }

    public PlayerAliveEventArgs(bool deadOrAlive)
    {
        Alive = deadOrAlive;
    }
}

in another class i tie a method to the event...

public void Form_Load()
{
     game.GameOver += Form1_GameOverMethod; // it shows the error here.
     it says no overload of this method matches System.Eventhandler
}

public void Form1_GameOverMethod(object sender, PlayerAliveEventArgs e)
{
    if (!e.Alive)
    {
        GameTimer.Enabled = false;
        gameOver = true;
        Refresh();
    }
}

The error is:

Method doesn't exist in this context.

Why is that?

okay i made the following changes:

 public void Form1_GameOverMethod(object sender, EventArgs e)
 {
      PlayerAliveEventArgs d = (PlayerAliveEventArgs)e;
      if (!d.Alive)
      {
      }
 }

is it okay now? or will it fire some problems when i run it (i want to save myself debugging latter on..)

Upvotes: 0

Views: 101

Answers (4)

faester
faester

Reputation: 15076

Because you method is named Form1_GameOverMethod.

Upvotes: 1

abatishchev
abatishchev

Reputation: 100258

Event declaration:

public event EventHandler<PlayerAliveEventArgs> GameOver;

Subscription:

game.GameOver += Form1_GameOverMethod;

Event handler:

private void Form1_GameOverMethod(object sender, PlayerAliveEventArgs e)
{
    bool alive = e.Alive;
}

Firing:

if (this.GameOver != null) // does any subscriber exist?
{
    this.GameOver(this, new new PlayerAliveEventArgs(..));
}

Upvotes: 4

AbdouMoumen
AbdouMoumen

Reputation: 3854

GameOverMethod doesn't exist in that context indeed. what exists however (and that's what you intended I suppose) is Form1_GameOverMethod.

A couple more remarks. First, before firing an event, you should check whether someone has subscribed to it or not.

if(GameOver!=null)
    GameOver(this, new PlayerAliveEventArgs(Alive));

Second, I believe you should change you event declaration to be:

public event EventHandler<PlayerAliveEventArgs> GameOver;

Hope this helps

Upvotes: 0

anon
anon

Reputation:

You should use

game.GameOver += Form1_GameOverMethod;

Upvotes: 1

Related Questions