mjr
mjr

Reputation: 43

Create disposable object via factory in Using statement

Assume base class Foo implements IDisposable. Classes FooA and FooB inherit class Foo. A simple factory method, FooFactory.Create() returns either a FooA or FooB object depending on the needs of the client.

In the client code below (FooTest module), attempting to use the factory method in a 'Using' statement results in the following compile error:

'Using' resource variable must have an explicit initialization.

I'd appreciate any suggestions (best practices) regarding an implementation that would support the instantiation of FooA or FooB (specified by client) via the Using statement. A Factory isn't required - it's simply the approach I tried. Ideally, I'd like FooA and FooB to be separate classes with a common base class or interface.

Thanks in advance for any help you might provide.

Public Module FooTest

    Public Sub Test()
        'the following compiles:
        Dim f As Foo = FooFactory.Create("A")
        f.DoWork()
        f.Dispose()
        'the following causes a compile error:
        ''Using' resource variable must have an explicit initialization.
        Using f As FooFactory.Create("A")
            f.DoWork()
        End Using
    End Sub

End Module

Public Module FooFactory

    Public Function Create(ByVal AorB As String) As Foo
        If AorB = "A" Then
            Return New FooA
        Else
            Return New FooB
        End If
    End Function

    Public Class FooA : Inherits Foo
    End Class

    Public Class FooB : Inherits Foo
    End Class

    Public MustInherit Class Foo : Implements IDisposable
        Public Overridable Sub DoWork()
        End Sub
        Public Overridable Sub Dispose() Implements IDisposable.Dispose
        End Sub
    End Class

End Module

Upvotes: 3

Views: 386

Answers (1)

Stuart Whitehouse
Stuart Whitehouse

Reputation: 1441

You just have the syntax wrong on the Using line. Write it just like the Dim, replacing Dim with Using:

Using f As Foo = FooFactory.Create("A")

You can't say "As FooFactory.Create" since a type must follow the "As" keyword.

Upvotes: 7

Related Questions