Friday, May 6, 2011

VB.NET WithEvents keyword behavior - VB.NET compiler restriction?

I'm working on becoming as familiar with C# as I am with VB.NET (the language used at my workplace). One of the best things about the learning process is that by learning about the other language you tend to learn more about your primary language--little questions like this pop up:

According to the sources I've found, and past experience, a field in VB.NET that is declared as WithEvents is capable of raising events. I understand that C# doesn't have a direct equivalent--but my question is: fields without this keyword in VB.NET cannot raise events, is there a way to create this same behavior in C#? Does the VB compiler simply block these objects from having their events handled (while actually allowing them to raise events as usual)?

I'm just curious; I don't have any particular application for the question...

From stackoverflow
  • In C# you simply wouldn't add a handler for any events. Assuming the class has public events and we're not modifying it, you can't stop someone from adding an event handler.

    Will Marcouiller : On the other hand, you simply have to define the eventHandler += yourHandler.
  • Omitting WithEvents doesn't block members from raising events, it just stops you from using the 'handles' keyword on their events.

    Here is a typical use of withevents:

    class C1
        public WithEvents ev as new EventThrower()
        public sub catcher() handles ev.event
            Debug.print("Event")
        end sub
    end class
    

    Here is a class which doesn't use WithEvents and is approximately equivalent. It demonstrates why WithEvents is quite useful:

    class C2
        private _ev as EventThrower
        public property ev as EventThrower
            get
                return _ev
            end get
            set(byval value as EventThrower)
                if _ev isnot nothing then
                    removehandler _ev.event, addressof catch
                end if
                _ev = value
                if _ev isnot nothing then
                    addhandler _ev.event, addressof catch
                end if
            end set
        end property
        public sub new()
            ev = new EventThrower()
        end sub
        public sub catcher()
            Debug.print("Event")
        end sub
    end class
    
    STW : I guess I'd never noticed that--probably because the only time I pay attention to it is when I get the error :-)

0 comments:

Post a Comment