Adding NativeEventHandler

Most of you probably know this shortcut, but for those how don’t, -here is a shortcut when adding native event handlers.

If you add an event handler like this

public class Program
{
public static void Main()
{
  InterruptPort   Bryter = new InterruptPort((Cpu.Pin)FEZ_Pin.Interrupt.LDR,true,Port.ResistorMode.PullUp,Port.InterruptMode.InterruptEdgeBoth);
  Bryter.OnInterrupt += <tab><tab>

And after the += presses tab twice, Visual Studio will build your handler for you like this.


public static void Main()
{
InterruptPort   Bryter = new InterruptPort((Cpu.Pin)FEZ_Pin.Interrupt.LDR,true,Port.ResistorMode.PullUp,Port.InterruptMode.InterruptEdgeBoth);
Bryter.OnInterrupt += new NativeEventHandler(Bryter_OnInterrupt);
}

static void Bryter_OnInterrupt(uint data1, uint data2, DateTime time)
  {
    throw new NotImplementedException();
  }

This also works for other things like:

-if
-for
-while
etc.

It works for almost everyting 8)

And you can remove some redundant things, here :wink:

Bryter.OnInterrupt += Bryter_OnInterrupt;

So these lines are identical?


Bryter.OnInterrupt += Bryter_OnInterrupt;
Bryter.OnInterrupt += new NativeEventHandler(Bryter_OnInterrupt)

;

I didnt know that, thanks.

Yes they are !

Yup,try it out :slight_smile:

I did and it worked no problems there :slight_smile:

But can anyone explain to me why Microsoft hasnt done it like that?
Anyone reading my post has probably fingered out that Im quit new to C# and struggle to get the hang of it. So the ‘new part has no bearing on the underlying code and GC?

I would appreciate if anyone could explain this to me.

This one won’t help much, but still : [url]c# - What constitutes 'redundant delegate creation'? - Stack Overflow

To me, considering the following code :

OutputPort led = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.LED, false);
led.OnInterrupt += new NativeEventHandler(led_OnInterrupt);

I would say that since OnInterrupt is of type NativeEventHandler, there’s no need to somehow “cast” again the associated delegate method with NativeEventHandler. The compiler is smart enough to detect that the led_OnInterrupt method will be used as an event handler. Hence the redundancy of the explicit declaration.