I'm trying to determine if there's a way in Visual Basic 2008 (Express edition if that matters) to do inline collection initialization, a la JavaScript or Python:
Dim oMapping As Dictionary(Of Integer, String) = {{1,"First"}, {2, "Second"}}
I know Visual Basic 2008 supports array initialization like this, but I can't seem to get it to work for collections... Do I have the syntax wrong, or is it just not implemented?
A collection is a class, so you must declare an instance of the class before you can add elements to that collection. If your collection contains elements of only one data type, you can use one of the classes in the System. Collections. Generic namespace.
First example. We can use several syntax forms for String Lists—these same syntax forms can be used for other Lists. Version 1 We create a List by passing an array of values to the List constructor. We print the first value. Version 2 We use a more verbose syntax for the List constructor call.
Object initializers enable you to declare and instantiate an instance of a class in a single statement. In addition, you can initialize one or more members of the instance at the same time, without invoking a parameterized constructor.
Collection classes serve various purposes, such as allocating memory dynamically to elements and accessing a list of items on the basis of an index, etc. These classes create collections of objects of the Object class, which is the base class for all data types in VB.Net.
Visual Basic 9.0 doesn't support this yet. However, Visual Basic 10.0 will.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With