Q & A Visual Basic – Declaring Arrays using WithEvents

Q:

Why can’t we declare arrays with the WithEvents keyword? I’ve read the MSDN documentation on WithEvents but it doesn’t explain why this is the case.

 

 

doc excerpt

Part

Description

WithEvents

Optional. Keyword specifying that varname is an object variable used to respond to events triggered by an ActiveX object. WithEvents is valid only in class modules. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents. You can't use New with WithEvents.

 

 

A:

Simple: the reason you can’t do this is because it’s not part of the language. Checkout the language specification for Array-Creation:

ArrayTypeName ::= TypeName ArrayTypeModifiers

ArrayTypeModifiers ::= ArrayTypeModifier+

ArrayTypeModifier ::= ( [ RankList ] )

RankList ::=

    , |

   RankList ,

ArrayNameModifier ::=

   ArrayTypeModifiers |

   ArraySizeInitializationModifier

Just notice that the WithEvents keyword is only mentioned within the “Instances and Share Variables” portion of the language spec.

VariableMemberDeclaration ::=

   [ Attributes ] [ VariableModifier+ ] [ Dim ] VariableDeclarators

      LineTerminator

VariableModifier ::=

   AccessModifier |

   Shadows |

   Shared |

   ReadOnly |

   WithEvents

VariableDeclarators ::=

   VariableDeclarator |

   VariableDeclarators , VariableDeclarator

VariableDeclarator ::=

   VariableIdentifiers [ As TypeName ] |

   VariableIdentifier [ As [ New ] TypeName [ ( ArgumentList ) ] ]

      [ = VariableInitializer ]

VariableIdentifiers ::=

   VariableIdentifier |

   VariableIdentifiers , VariableIdentifier

VariableIdentifier ::= Identifier [ ArrayNameModifier ]

VB6 and VB.NET have virtually the same language spec for object declaration so you’ll see that this holds true for both versions of the language. You’ll see in VB6 that you can declare a variable withevents on a class object that doesn’t expose events and everything is fine and dandy. In .NET you’ll get a compiler error stating that the object doesn’t raise any events.

Now for an explanation as to why the language was designed this way: Technically it doesn’t really make sense to allow events on an array since it doesn’t expose any events and as such it wasn’t added to the language. I’m assuming the functionality people look for is that by declaring an array using withevents you could wire up the events for all of the elements within the array. . Well, the most likely reason this wasn’t added to the language is because of object lifetime and creation. In order to raise events you have to know the address of the eventhandler. In the case of an array things get tricky. Things like “ReDim”, moving objects around, adding/removing elements, etc make this an extremely complex problem. This is quicksand to try to implement so it was probably deemed easier just to not allow.