Tuesday, May 27, 2008

How to Create Generic Function

Level: Beginner

Knowledge Required:
Generics in Visual Basic

Introduction:
This article discusses how to create a Generic Function. Example: Create a Generic Function which is used to Find a Form in Open Forms. Useful for:

1) Preventing to create another instance of a Form
2) Finding a De-Activated / NOT Focused Window and set Focus on it

Description:
In my starting Post I discussed a situation where we require to find a Form which is opened. Now we will create a Generic Function which will return that particular type of Form.

Public Function GetWindow(Of T As Form)() As Form
For Each frmEach As Form In My.Application.OpenForms
If TypeOf frmEach Is T Then
Return frmEach
End If
Next
Return Nothing
End Function
Usage:
Public Sub ShowForm2()
' We will create a new instance of Form2
Dim frmNew As Form2
' Call GetWindow() function which returns that type of Window if open
frmNew = GetWindow(Of Form2)()
' GetWindow() returns NOTHING if window NOT found
If frmNew IsNot Nothing Then
frmNew.Show()
frmNew.Focus()
Else
' OK it means Window NOT Opened so create new instance
frmNew = New Form2
frmNew.Show()
End If
End Sub

No comments: