tags:

views:

146

answers:

5

Hello everybody

In my personal project ,i have never used Events.I have never feel it neccesary.Especially using Events create some problems about restriction on methods with same parameters and this is why i haven't used it any.What is benefit of using it ? When time and where we need it ?

Edit: Using Events is more for closed source libraries? Because we can not attach any method to existing closed source methods so Events help us about this problem ? Because in opened source, we can easily add our methods into end of the methods.

+1  A: 

Well, when you need observers to react to events which occur within your objects :)

The most obvious examples are UI components - a Button exposes an event which is fired when the button is clicked, for example.

If you don't have anything which naturally feels like it's exposing events, then it's fine not to use them. If, however, you have anything where other parties are interested in reacting to things happening in your objects, you should consider events - and/or the Reactive Extensions framework.

Jon Skeet
A: 

You need not use it. However, it is just a shortcut for what you will anyway end up doing, if the problem you are solving requires it. But since you are using C# .NET which has a shortcut, you will be better off using them. It more C#ish.

tathagata
A: 

Events are used for callbacks when a server may call a client's method. Such option exists not only in c# (f.e. function pointers in c++). Of cause you may not use events build up your code avoiding them. I'd recomend to get to know them better and understand their advantages.

Arseny
+1  A: 

Most obvious example, events are particulary useful when dealing with GUIs. Your application user usualy interacts with front-end part of your code (graphical interface in this case), while most logic is "hidden".

I'm sure you've seen this schema - you press the button, something "happens" in the background, you are presented operation result. You don't need to know what exactly happened, you are only interested in the string that appeared in application window saying "Your ticket has been booked.".

Same story with user interface. In most cases it doesn't need to know (nor it should) how exactly application logic is implemented, or what does it do. It's there to present results and interact with user.

How that works in .NET? Consider continuation of ticket-booking example, part of say TicketBooker class:

public event Action BookingSuccessful;

public void BookTicket()
{
    // lot of complex steps that should run in background
    this.ValidateInputData();
    this.GetTicketInfo();
    this.CheckUserInfo();
    this.SendDataToOperator();
    this.WithdrawMoney(); 
    // ...and perhaps lot more stuff you might want to do 
    // in order to book ticket
    if (booked)
    {
        // we're done: let's raise event which will 
        // notify all interested observers 
        this.BookingSuccessful();
    }
}

As you can see, BookTicket method might take long to complete, might have many complex steps, most of which - as a user - we don't want to know. We just need the information whether we booked it or not.

Knowing that, we don't want user to wait with hung up application because ticket is being booked. User still should be able to interact with it (to some extent of course). Hence, user interface classes want to subscribe to TicketBooker class event.

TicketBooker tb = new TicketBooker();
tb.BookingSuccessful += this.ShowSuccessMessage;

// ... somewhere here we call tb.BookTicket() method to run in background
// once it completes (with success), it will raise BookingSuccessful event
// which will cause ShowSuccessMessage to execute, as we subscribed it

public void ShowSuccessMessage()
{
    // simply display success message in interface, eg. by setting label text
}

The entier picture is of course much bigger than this simple example. Events help with separating application presentation layer from data model/business logic, they deal with notification of interested objects about changes in your objects and so on.

For starters, you can check this tutorial on MSDN: Events Tutorial

Checking how Model-View-Controller pattern works might provide better understanding too: MVC.

And as always, SO is full of resources on this topic, just search for questions tagged events & .net.

jimmy_keen
+5  A: 

Oh, I had the very same problem. I understood the concept of events because I used them heavily in JavaScript but I just couldn’t justify the use of events in a C# application. I mean, I used server OnClick etc, but I couldn’t understand why would I use events anywhere else.

Funny story actually, because I learnt it the hard way when I was working on my ORPG game. Consider following code:

class Player
{
    private int health;
    public int Health
    {
        get
        {
            if (health <= 0)
            {
                Die();
            }

            return health;

        }

        set
        {
            health = value;
        }
    }

    public void Die()
    {
        // OMG I DIED, Call bunch of other methods:
        // RemoveFromMap();
        // DropEquipment(); etc
    }
}

Makes sense, right? Player has no health so I'm calling Die(). Die method is then doing whatever it is supposed to do - kill the player.

My problems started when I wanted to reuse this class in both Server and Client application of my ORPG game. It's quite easy to notice that Die() method should do different things, depending on where the 'Kill' is performed - on server it should update all sorts of different data - on client it should i.e. do something with graphics.

Additionally - what if I wanted the Die() method to do different things, depending on the type of Player? After all user controlled Players should do different things when they are killed compared to computer/AI controlled Players (NPCs).

And so, I was forced to use events:

class Player
{
    public event DieHandler Die;
    public delegate void DieHandler(Player sender, EventArgs e);
    public virtual void OnDie(EventArgs e)
    {
        if (Die != null)
            Die(this, e);
    }

    private int health;
    public int Health
    {
        get
        {
            if (health <= 0)
            {
                onDie(new EventArgs());
            }

            return health;

        }

        set
        {
            health = value;
        }
    }
}

And now, when I create new player, I can assign any method to its DieHandler:

Player player = new Player("Joe");
player.Die += Client.Players.PlayerDie;

Player npc = new Player("Cookie Monster");
npc.Die += Client.Npcs.NpcDie;

where Client.Npcs.Die and Client.Players.Die is one of following:

public void NpcDie(Player sender, EventArgs e)
{
    //who hoo, I can be implemented differently
    //I can even check if sender.Health <= 0
}

public void PlayerDie(Player sender, EventArgs e)
{
}

As you can see now we've got the flexiblity to attach any 'matching' method to our Die handler. We send the Player object as sender attribute and any defined EventArgs in e. We can use EventArgs to send additional information, i.e. - e.NameOfTheKiller, e.LastHitAtTime etc etc. The best thing is that you can define your own EventArgs class so you can send additional info when you spawn your event.

Wow... this post is long. I hope you get it now.

So again - use events everywhere when you want to 'inform the external world' about some particular state of your object and handle this change appropriately. It will make your code more flexible and a lot easier to maintain.

rochal
Good response, but aren't you effectively using events to avoid sub-classing Player in this example?
JonB
In my actual code both Player and Npc inherit from GameBeing. The Server-Client example is better because I must do different stuff with Player/Npc object depending where this class is used.
rochal
Please correct me if i understood your example right. You were using same class on server and client side and the problem was die method was doing different jobs on both side and you couldn't reuse same class without modify it. So events helped to overcame this problem, right? You can attach any method for Die event in both side.This help us about code reusability ,seperating codes into more pieces and more flexible structure.
Freshblood
Precisely. And if I ever wanted to use my Player class somewhere else, I could easily do it, because even thought Player class can take care of itself internally, it is still updating the 'environment' about its state. And I achieved that, using events.
rochal