Tuesday, March 23, 2010

.NET: Activator Class (Create dynamic instance of an object)


In my recent developments, I had a situation to create a dynamic instance of a Crystal Report where the Crystal Report File name is dynamically derived from the table settings.
In general scenarios, without knowing the class name it is almost impossible to construct an instance of that class at runtime. In order to achieve the above, use "Activator.CreateInstance"

Activator Class

Contains methods to create types of objects locally or remotely, or obtain references to existing remote objects.

Activator.CreateInstance

The CreateInstance method creates an instance of a type defined in an assembly by invoking the constructor that best matches the specified arguments. If the instance is created locally, a reference to that object is returned. If the instance is created remotely, a reference to a proxy is returned.

Example:

Public ReadOnly Property GetCrystalReportInstance
(Optional
ByVal pReportName As
String = "") As ReportClass
Get
    Dim crReport As ReportClass = Nothing
    Dim sReportClassName As String = String.Empty    
    Dim rpttype As Type
Try
'NOTE : Report Name should always be a fully qualified name prefixed with your Namesspce.
sReportClassName = pReportName.Replace(".rpt", "")
rpttype = Type.GetType(sReportClassName, True, True)
crReport = CType(Activator.CreateInstance(rpttype),ReportClass)
Catch ex As Exception
'ignore errors and return crReport

End Try

Return crReport
End Get
End Property

No comments:

Post a Comment