Question

I have the following code that has worked fine for months, but I forgot to create this class with Option Strict On so now I am going back to clean up my code correctly, however I haven't been able to figure out a way around the following issue.

I have a local variable declared like this:

Private _manageComplexProperties

Now with option strict, this isn't allowed due to no As clause which I understand, however the reason that it is like this is because the instance of the class that will be assigned to it takes a type parameter which isn't known until run time. This is solved by the following code:

Private _type As Type
*SNIP OTHER IRRELEVANT VARIABLES*

Public Sub Show()

    Dim requiredType As Type = _
        GetType(ManageComplexProperties(Of )).MakeGenericType(_type)

    _manageComplexProperties = Activator.CreateInstance(requiredType, _
         New Object() {_value, _valueIsList, _parentObject, _unitOfWork})

    _result = _manageComplexProperties.ShowDialog(_parentForm)
    If _result = DialogResult.OK Then
        _resultValue = _manageComplexProperties.GetResult()
    End If

End Sub

Again option strict throws a few errors due to late binding, but they should be cleared up with a cast once I can successfully declare the _manageComplexProperties variable correctly, but I can't seem to get a solution that works due to the type parameter not known until run time. Any help would be appreciated.

Was it helpful?

Solution

Declare your variable as Object

Private _manageComplexProperties as Object

And then you will have to persist with reflection, e.g. to call ShowDialog method:

Dim method As System.Reflection.MethodInfo = _type.GetMethod("ShowDialog")
_result = method.Invoke(_manageComplexProperties, New Object() {_parentForm})

OTHER TIPS

You have to use option infer on on the top of your vb file. It enables local type inference.

Using this option allows you to use Dim without the "As" clausule, it is like var in C#.

IntelliSense when Option Infer and Option Strict are off

enter image description here

IntelliSense when Option Infer is on (as you can see it has type inference)

enter image description here

If you do not want to use option infer on, you will have to declare the variable matching the type of the one returned by Activator.CreateInstance

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top