How to use Activator in VB.NET

Activator Class contains methods to create types of objects locally or remotely and the Activator.CreateInstance is used to create the object by the use of a fully qualified string class name.
  • 6946

Activator Class contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. The factory method is used Activator.CreateInstance to create the object by the use of a fully qualified string class name. Activator class is used dynamically to construct objects at run time. And the Activator.CreateInstance is makes the method completely agnostic as to the class that is being created. In other words, the code will never make a direct reference to the class name. 
Activator is used with so-many member's like some are:

  • CreateInstance(Of T)
  • GetType
  • MemberwiseClone
  • ToString and etc.

Here I am taking an example of Activator with CreateInstance(Of T): 
Example:

Imports
 System.Reflection
Imports
 System.Text
 
Module
 Test
    Sub Main()
        Dim obj As Object = Activator.CreateInstance(GetType(StringBuilder))
 
        Dim a As StringBuilder = CType(obj, StringBuilder)
        a.Append("Result:")
        Console.WriteLine(a)
 
        Dim i As System.Runtime.Remoting.ObjectHandle = _
            Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase, _
                                         GetType(SomeType).FullName)
 
        Dim j As SomeType = CType(i.Unwrap(), SomeType)
 
        j.DoSomething(10)
    End 
Sub
 
    Class 
SomeType
        Public Sub DoSomething(ByVal x As Int32)
            Console.WriteLine("150 + 275 + {0} = {1}", x, 150 + 275 + x)
            Console.ReadLine()
        End 
Sub
    End 
Class
End Module 
Output:

sss.gif

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.