Luna Luna - 3 months ago 17
C# Question

C# - Casting EventArgs to a generic Event type

I'm working on a game just for fun, I'm attempting to implement events but I get the error:


Error CS0305: Using the generic type 'Game.NPC.Events.MurderEventArgs' requires 2 type arguments (CS0305) (Game)


The code which is raising the event:

public event EventHandler<EventArgs> OnMurderEvent;

public void RaiseMurderEvent<TVictim, TMurderer>(TVictim npcVictim, TMurderer npcMurderer)
{
if (OnMurderEvent != null)
{
OnMurderEvent(this, new MurderEventArgs<TVictim, TMurderer>(npcVictim, npcMurderer));
}
}


My code which is handling the event:

npc.OnMurderEvent += HandleMurderEvent;
npc.RaiseMurderEvent<Victim, Murderer>(null, null);

static void HandleMurderEvent(object sender, EventArgs e)
{
Console.WriteLine((MurderEventArgs)e);
}


The casting won't work because it doesn't have the generic types, can anybody help?

Answer

Suppose your MurderEventArgs looks like that:

class MurderEventArgs<TVictim, TMurderer> : EventArgs
{
    public MurderEventArgs(TVictim victim, TMurderer murderer)
    {
        //your code here
    }
}

You may change your EventHandler to:

class EventRaiser<TVictim, TMurderer>
{
    public event EventHandler<MurderEventArgs<TVictim, TMurderer>> OnMurderEvent;

    public void RaiseMurderEvent(TVictim npcVictim, TMurderer npcMurderer)
    {
        if (OnMurderEvent != null)
        {
            OnMurderEvent(this, new MurderEventArgs<TVictim, TMurderer>(npcVictim, npcMurderer));
        }
    }
}

And your usage would look like this:

static void FireAndForget<TVictim, TMurderer>(TVictim victim, TMurderer murderer)
{
    var npc = new EventRaiser<TVictim, TMurderer>();
    npc.OnMurderEvent += HandleMurderEvent<TVictim,TMurderer>;
    npc.OnMurderEvent += HandleMurderEventAlt;
    npc.RaiseMurderEvent(victim, murderer);
}

static void HandleMurderEvent<TVictim, TMurderer>(object sender, EventArgs e)
{
    var murderEvent = (MurderEventArgs<TVictim, TMurderer>)e;
    //do something with the event
}

//or alternatively
static void HandleMurderEventAlt<TVictim, TMurderer>(object sender, MurderEventArgs<TVictim, TMurderer> e)
{
    //do something with the event
}
Comments