Jump to content
  • Advertisement
Sign in to follow this  
Dark Schneider

[.net] Events with parameters (arguments)

This topic is 4005 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'd like to have Eventhandlers that accept parameters, for example, to store the TextBox values in our data vars I'd like to have something like: textBox.Leave += new EventHandler(function(ref param)); where 'param' is a class variable and function is something like: private void function(object sender, System.EventArgs e,ref Type param) { param=ConvertToParamType(((TextBox) sender).Text); } With this, we only need to assign the eventhandlers like: textBox1.Leave += new EventHandler(function(ref param1)); textBox2.Leave += new EventHandler(function(ref param2)); textBox3.Leave += new EventHandler(function(ref param3)); textBox4.Leave += new EventHandler(function(ref param4)); with only 1 function, but I don't know how to do this. See that I put very generic code, functions requires some try-catch and more, but this is not the case, I only want to know how to create EventHandlers with params, because actually I must to repeat the function code for every TextBox because anyone use a different class variable, and I think is repeat work and create a huge code for nothing usefull. Thanks.

Share this post


Link to post
Share on other sites
Advertisement
The standard way to do this is to create your own custom event args class and use the EventHandler<> delegate creator, like so:


public class MyClass
{
public event EventHandler<MyEventArgs> MyEvent;

protected virtual void RaiseMyEvent( MyEventArgs e )
{
if( MyEvent != null )
MyEvent( this, e );
}
}

public class MyEventArgs : EventArgs
{
public MyEventsArgs( myParamHere )
{
}
}

MyClass foo = new MyClass();
foo.MyEvents += new EventHandler<MyEventArgs>( eventHandler );

void eventHandler( object sender, MyEventArgs e )
{
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!