Drstein99 Posted September 25, 2004 Posted September 25, 2004 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)? Quote www.DRSTEIN99.com www.RAIDGEAR.net www.THERE.com -> Tell them DrStein99 sent ya!
Administrators PlausiblyDamp Posted September 25, 2004 Administrators Posted September 25, 2004 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 Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.