Use of CreateInstance method to construct an array in VB.NET

Array.CreateInstance method provides a way to construct arrays in memory using parameters.
  • 3531

You want to create an array that has elements of a certain type, which may not be known at compile-time, and also of a certain size. Using the Array.CreateInstance factory method, you can create arrays using a Type reference and some integers for the size. The Array class is equipped with the CreateInstance() method that is overloaded with various versions. One of the versions of this method uses the following syntax:

Syntex

Overloads Public Shared Function CreateInstance(ByVal elementType As Type,ByVal length AsIntegerAs Array

The Array.CreateInstance method provides a way to construct arrays in memory using parameters. You do not need to know at compile-time what type of array will be created. As a factory method, the Array.CreateInstance returns the abstract base class Array; you can cast this to a specific type of array. You had created an array using the CreateInstance() method of the Array class, you can access each member using its index in its parentheses to initialize it.

Now to learn more see the example of Array.CreateInstance. In this example we use Option Strict, and we use SetValue to assign array elements.

Example

Option Strict On
Module
 Module1
    Sub Main()
        Dim Alpa As System.Array
        Dim IEn As System.Collections.IEnumerator
        Alpa = System.Array.CreateInstance(GetType(String), 6)
 
        Alpa.SetValue("h", 0)
        Alpa.SetValue("d", 1)
        Alpa.SetValue("b", 2)
        Alpa.SetValue("c", 3)
        Alpa.SetValue("k", 4)
        Alpa.SetValue("o", 5)
 
        IEn = Alpa.GetEnumerator
        Console.WriteLine("Value's")
        Do While IEn.MoveNext
            Console.WriteLine(IEn.Current())
        Loop
 
        Array.Sort(Alpa)
        Array.Reverse(Alpa)
        IEn = Alpa.GetEnumerator
        Console.WriteLine("Sorted Value's")
 
        Do While IEn.MoveNext
            Console.WriteLine(IEn.Current())
        Loop
        Console.ReadLine()
    End 
Sub
End Module

Output

a.gif

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.