Avoid creation of object

Kurt

0
Joined
Feb 14, 2003
Messages
113
Location
Los Angeles
A user of my class needs to supply some information to the constructor of the class. Then the constructor checks if the parameters that where passed can describe a valid instance or not. If not I give the user a warning, but I would also like to drop the creation of the object itself - as if the constructor was never called!
Is this possible?
 
You could throw an exception if the parameters arent valid but that wouldnt get round this problem.

You could make the Sub new private (or protected) and provide a shared public sub that accepts the parameters and does the validation - if everythings fine it creates and returns a valid instance, if not it returns nothing.
e.g.

Code:
Public Class TestClass

    Private X, Y As Integer

    Private Sub New(ByVal i As Integer, ByVal j As Integer)
        X = i
        Y = j
    End Sub

    Public Shared Function CreateTest(ByVal i As Integer, ByVal j As Integer) As TestClass
        If i < j Then   Do your validation
            Dim tmp As New TestClass(i, j)
            Return tmp
        Else
            Return Nothing
        End If
    End Function

End Class

this can be called like
Code:
Dim t As New TestClass  invalid
Dim t1 As TestClass
t1 = TestClass.CreateTest(1, 2) valid instance returned
Dim t2 As TestClass
t2 = TestClass.CreateTest(2, 1) nothing is returned
 
I thought shared (static) methodes only could use other static members. The constructor must be an exception then, or is actually always static from nature. Logical enough, otherwise an instance would be needed to create an instance...
 
Its not directly accessing a non-shared member though - its creating a new instance, which calls the new instances constructor as normal.
 
Back
Top