The online racing simulator
.NET C# Callbacks
(6 posts, started )
#1 - PoVo
.NET C# Callbacks
Hi,

I've recently been trying to get a callback system working for buttons in my project.

Anyway so currently I have a simple List<> which stores a class that should contain the button data and the callback.

The only problem is I'm not sure how to implement callbacks. I've been reading up on delegates and I can't come to a solution.

I basically want to be able to:
list[index].Callback(someMethodInSomeClass);

Basically the same way as it's done in InSimDotNet with packet bindings.

I've read through the InSimDotNet source and I still can't figure it out...

Any ideas?
You can store a callback using the .NET Action delegate type.

void SomeMethod() { }

// Create an action that points to the method.
Action methodToCall = new Action(SomeMethod);

.NET is smart enough to figure out what to do if you leave out the object instantiation.

// Does the same thing as above.
Action methodToCall = SomeMethod;

Then you can just call the action delegate like you would a normal method.

methodToCall();

If you want to pass a parameter it would look like this:

void SomeOtherMethod(string param1, int param2) { }

Action<string, int> otherMethod = SomeOtherMethod;

otherMethod("Hello", 1234);

If you want the method to return a value, you can use the builtin Func delegate type.

bool MethodWithReturn(string param1) { return true; }

// Use a func if there is a return value.
Func<string, bool> returnMethod = MethodWithReturn;

bool result = returnMethod("Hello");

There's a lot more to delegates, but that's enough to get you through most problems.
#3 - PoVo
Great! Thanks for your help.

The examples I was reading at Microsoft's help site weren't useful at all and made no sense!

Thanks for clearing it up
C# is based on events, so, basically using events is the fastest way of passing objects between classes and methods.

By saying "callbacks" i suppose you had "events" in mind tho. Easy to mix them up, if you had experience in programming on C (or derivatives of C, like PAWN).

So, for example your button class should have something like:

class SomeClass
{
public event EventHandler clicked;
...
if(Conditions_for_callback_are_met)
{
clicked(this, EventArgs.Empty);
}
...
}

then on some other class where you're creating the object, you can simply:
SomeClass someObject = new SomeClass();
someObject.clicked += new EventHandler(someEvent_Fired);

followed by:
private void someEvent_Fired(object sender, EventArgs e)
{
// add type cast to get the object, that fired the event;
SomeClass objectPassed = (SomeClass)sender;
...
}

and handle the event.

Hope that helped.

Disclaimer:
I learned this programming C# (not InSim related, since im demo user).
#5 - PoVo
Nice. Would there be any real good advantages to switch from actions to event handlers?

.NET C# Callbacks
(6 posts, started )
FGED GREDG RDFGDR GSFDG