Search code examples
.netformsoption-strict

Running a sub on a form with option Strict ON


I'm trying to clean up my coding practices, and came across this I could not solve.

With option strict on, how you you find an instance of a form and run a public sub on said instance?

For example in an inventory package, i have a shortcut to checkout a part, which finds if a check out form is open and runs Checkout.AddID(ID as Integer). EG:

For Each Form In Application.OpenForms
    If Form.Name = "FRMCheckout" Then
        Form.AddIDToList(PartID)
    End If
Next

This works fine with option strict off. However, turn it on and modify it to suit such as:

For Each Form As Windows.Forms.Form In Application.OpenForms
    ' If Form.Name = "FRMCheckout" Then EDIT: Dropped this in leu of this:
    If TypeOf (Form) Is FRMCheckout Then
        Form.AddIDToList(Ctype(PartID, Integer))
    End If
Next
     

Throws the error (obviously) that .AddIDToList is not a member of Forms.form.

Changing to For Each Form as ProgramNamespace.FRMCheckout would throw 'Cannot cast type form to FRMcheckout' when ever the for loop hits a normal form.

What would be a way to accomplish this without turning off option strict?


Solution

  • Look for OfType enumerable extension, the code is just

    For Each checkout In Application.OpenForms.OfType(Of FRMCheckout)()
        checkout.AddIDToList(Ctype(PartID, Integer))
    Next
    

    Now the loop returns only the forms of type FRMCheckout and the iterator variable is already strongly typed so you could call its public methods and properties without any conversion. Of course all the grunt work is done inside the OfType extension so it is not really an improvement in performance if any is expected but just a more clear way to write and understand a piece of code