new object, return nothing

Drstein99

Well-known member
Joined
Sep 26, 2003
Messages
283
Location
Audubon, Nj
I have a custom class. I want to send the NEW command, and if the data doesnt validate - i want to return NOTHING

How can i call the NEW command on my class and return NOTHING and totally not new the object (if data is invalid)?
 
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.
Code:
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
Code:
    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
 
Back
Top