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