Saturday, October 4, 2008

Event Null Checking In VB.NET Before It Raise

For Example In C#

class MyClass
    {
        public delegate void MyEventHandler(int i);
        public event MyEventHandler MyEvent;

        public MyClass()
        {
        }

        public void FireEvent()
        {
            if (MyEvent != null)
            {
                MyEvent(10);
            }
        }
    }

In above example we check  MyEvent has reference or not by checking if(MyEvent != null) in FireEvent Method. So Event only raise when it has reference.

In VB.NET raiseevent internally check this thing. but if you want to manually check then use following method.

VB.NET Example:

Public Class MyClass1
    Public Event MyEvent(ByVal i As Integer)
    Public Sub New()
    End Sub
    Public Sub FireEvent()
        If MyEventEvent IsNot Nothing Then
            RaiseEvent MyEvent(10)
        End If
    End Sub
End Class

In VB.net that is not necessary to create delegate. You can directly create event. If you want to check that event has reference or not if you have to Add “Event” extra word at the end of Event Name . In above example out event is MyEvent so we did check MyEventEvent is nothing or not. We can not directly check MyEvent is not nothing in VB.NET.

One more thing to know VB.net allow us to create event directly ( Without creating delegate). But implicitly it create delegate that has same name like MyEventEvent. Suppose you declare event Add then AddEvent delegate automatically created. (Please see below image).

vbnetevent

No comments: