views:

477

answers:

5

This should be a quick one. Is it possible to do something like this:

[Callback(funtionY)]
void functionX()
{
}

void functionY()
{
}

So that when functionX is called, functionY is called automatically too? Reason I ask is because I'm going to implement networking functionality to a small XNA based game engine, and I want to mark functions as Synched, to mark that when a function gets called it should be called across all clients.

Thanks.

+8  A: 

Sounds like you want Aspect-Oriented Programming.

I've used PostSharp for this before now, and it works pretty well.

Jon Skeet
That looks like a kick-ass library. Thanks!
Aistina
+5  A: 

You can probably do that quite easily with PostSharp, but in general: no; you'd have to call it explicitly.

Marc Gravell
+2  A: 

Is there some reason you can't do this:

void functionX()
{
    functionY();
    // ... etc
}

Based on the description in the question, that's a valid answer. I assume that you've considered it already, though.

Another possibility would be to use the eventing system to your advantage, something like (uncompiled):

event Action FunctionXCalled;

// somewhere in initialization...
MyCtor()
{
    FunctionXCalled += functionY;
}

void functionY() { }

void functionX()
{
    if(FunctionXCalled != null) FunctionXCalled();
    // ... etc
}
Greg D
+1 since it satisfies specified requirements :)
Mehrdad Afshari
Valid answer, but I don't want to call functionY manually in every method that needs to be synched, as there's bound to be a lot of them.
Aistina
Ummm, I'm not sure how adding a single function call is any more expensive than adding an attribute. And the function call doesn't add a dependency or cognitive dissonance for subsequent maintenance that the attribute adds.
Greg D
A: 

how about:

void functionX() {
   functionY();
   // Other implementation stuff
}

void functionY() {

}
workmad3
+3  A: 

Yes, you can, just create them as a delegate.

Action foo = functionX;
foo += functionY;

foo(); // both called

UPDATE: Jon (thanks) pointed out that invocation order is in fact determined. I would NEVER rely on this however. See comments.

leppie
The order *is* specified. It's guaranteed to be functionX followed by functionY. See the docs for Delegate.Combine.
Jon Skeet
It adds them in order, but whether it will be executed in the same order is not specified. The docs makes no mention of invocation order, and it should not matter, else I suspect they would have called it a SequentialDelegate, and not MulticastDelegate.
leppie
I stand corrected. I found the follwoing from the Delegate class page: 'During an invocation, methods are invoked in the order in which they appear in the invocation list.' IMO that is a not a very clever design decision. Now we will get users relying on invocation order...
leppie