|
-
Apr 30th, 2008, 09:12 AM
#1
Thread Starter
Frenzied Member
[2005] leave instance set to Nothing on failure of constructor
How would I achieve setting an instance of one of my classes to Nothing if the constructor fails?
Code:
Public Class MyClass
Public Sub New( Parm As Integer )
If Parm < 1 Then 'make the instance Nothing
End Sub
End Class
In the calling code doing Dim obj As New MyClass( 0 ) should leave obj set to Nothing.
This world is not my home. I'm just passing through.
-
Apr 30th, 2008, 10:56 AM
#2
Re: [2005] leave instance set to Nothing on failure of constructor
Make the constructor private and create a shared function to return an instance of the class. Something like this:
Code:
Public Class Class1
Private Sub New()
End Sub
Public Shared Function GetInstance(ByVal value As Integer) As Class1
If value <= 0 Then
Return Nothing
Else
Return New Class1()
End If
End Function
End Class
And use it like this
Code:
Dim myClass As Class1 = Class1.GetInstance(3)
-
Apr 30th, 2008, 10:58 AM
#3
Re: [2005] leave instance set to Nothing on failure of constructor
Why would you need to do this? Even if your Object takes up a ton of memory, if the constructor failed then the logic that would load, process or create data would not function I would imagine.
Just have it throw an exception on failure.
-
Apr 30th, 2008, 11:26 AM
#4
Thread Starter
Frenzied Member
Re: [2005] leave instance set to Nothing on failure of constructor
I wanted to do this because elsewhere in the code I test to see if the instance is Nothing to decide whether or not I'm going to do anything with it.
Thanks stanav - I've implemented your solution and it works nicely.
This world is not my home. I'm just passing through.
-
Apr 30th, 2008, 11:36 AM
#5
Re: [2005] leave instance set to Nothing on failure of constructor
In some articles I have read for C++, the case was made that under no circumstance should a constructor fail. I have totally forgotten the reason for that, but I've followed it. If I have a class that could fail to fully construct, I add a boolean member called ImValid, and just access that via a property which I test rather than testing for Nothing.
My usual boring signature: Nothing
 
-
May 1st, 2008, 03:10 AM
#6
Thread Starter
Frenzied Member
Re: [2005] leave instance set to Nothing on failure of constructor
I guess that if your class is intended to be used by other programmers their expectation would be that instantiating an object would always be successful. So, Shaggy's approach is better than what I've done.
Living and learning...
This world is not my home. I'm just passing through.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|