Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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?

qrt
  • Administrators
Posted

You could throw an exception if the parameters aren't valid but that wouldn't 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 everything's fine it creates and returns a valid instance, if not it returns nothing.

e.g.

 

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

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

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

  • 2 weeks later...
Posted
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...
qrt

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...