Page 1 of 1

raise statement: should this work?

PostPosted: Wed Nov 21, 2012 5:25 am
by kobi7
Hi Charles, (and everyone) should this code work?
I haven't tried in C# yet.
Am I doing something wrong here?

Code: Select all
sig Update
interface IView
   event finishedUpdate as Update

class X implements IView
   event finishedUpdate as Update

class MyProgram
   def main
      x = X()
      raise x.finishedUpdate

Re: raise statement: should this work?

PostPosted: Wed Nov 21, 2012 10:43 am
by Charles
Actually, in .NET, you're only supposed to raise events within the same class. See:

http://stackoverflow.com/questions/7903 ... in-c-sharp
http://stackoverflow.com/questions/4378 ... in-c-sharp

Besides the hacks shown in some answers above, you have two options. One is to switch from using an event to using a property whose type is the same as the delegate. The other is to provide a public method that raises the event like so:
sig UpdateHandler

interface IView

event finishedUpdate as UpdateHandler

class X implements IView

event finishedUpdate as UpdateHandler

def raiseFinishedUpdate
raise x.finishedUpdate

class MyProgram

def main
x = X()
x.raiseFinishedUpdate

But note that in most C# code I see, the method to raise an event is not public. Instead, events are raised from within the class to notify listeners when something interesting has happened for that class and object. Putting the logic for raising an event outside the class might be the event-based analog of "spaghetti code". So really the code should look more like:
sig UpdateHandler

interface IView

event finishedUpdate as UpdateHandler

class X implements IView

event finishedUpdate as UpdateHandler

def update
# do some update stuff
# and then:
raise x.finishedUpdate

class MyProgram

def main
x = X()
x.update

Also, note that I suffixed the sig name with "Handler". This is a common .NET style for declaring sigs/delegates that will be used for events.

I'll look into improving the Cobra compiler error checking and message.

Re: should this work?

PostPosted: Wed Nov 21, 2012 11:11 am
by Charles
FYI, in C#, if you try to raise an event for another class, the error message is:

The event 'A.Updated' can only appear on the left hand side of += or -= (except when used from within the type 'A')

... eh, not very friendly even if it's technically correct.

Re: should this work?

PostPosted: Wed Nov 21, 2012 6:02 pm
by Charles
I have now added a proper error check for this situation:
Code: Select all
Cannot raise events for other objects.

And made some minor updates at the Raise Statement wiki page.

Re: raise statement: should this work?

PostPosted: Thu Nov 22, 2012 5:14 am
by kobi7
thanks