Jump to content
Xtreme .Net Talk

Recommended Posts

  • Administrators
Posted

When you try to instantiate an object the New keyworld should always result in a valid object being returned - for this to just result in a null reference (I.e. the object is set to nothing) is extremely unusual behaviour. Within VB the only way for a Sub New to not return an object is for it to throw an exception, this however can be a performance hit and again is not standard behaviour.

 

A more OO way of acheiving this is to delegate the creation of class instances to a shared method - this may return Nothing.

 

i.e.

Public Class DemoClass

   Private _number As Integer

   Public ReadOnly Property Number() As Integer
       Get
           Return _number
       End Get
   End Property

   'Declared protected so cannot be called directly
   Protected Sub New(ByVal i As Integer)

   End Sub

   Public Shared Function CreateDemo(ByVal number As Integer) As DemoClass
       'for demonstration purposes we validate the number and only
       'create a class for odd numbers
       If number Mod 2 <> 0 Then
           Dim tmp As New DemoClass(number)
           Return tmp
       End If
       Return Nothing
   End Function

End Class

and this could be called like

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
       Dim c, d As DemoClass

       c = DemoClass.CreateDemo(1)     'works
       d = DemoClass.CreateDemo(2)     'Returns nothing

   End Sub

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

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...