Set Class Instance to Nothing During Instantiation?

J

Jeff Carver

I'm creating a class (using VB.NET) that must read data from a
database table during instantiation. If the data cannot be read
(connection problem, etc.), I want the instantiation to fail such that
the following "If" statement will evaluate to True:

Dim objGribble as New cGribble()
If objGribble Is Nothing Then ...

What code in the class's constructor (Sub New) would make that happen?
 
K

Karl

You can't. You're constructor can throw an exception...which how you
should do it anyways. if that isn't satisfactory, you can wrap your
constructor call in a static property of your class:

dim objGribble as cGribble = cGribble.CreateInstance()
if objGriggle is nothing then..


where CreateInstance() looks something like:

Public shared Property CreateInstance() as CGribble
get
try
return new cGribble()
catch ex as YourCustomException 'for the love of god don't
swallow this exception
return null
end try
end get
end property

karl
 
D

David Jessee

Or, here's another method. Do a Web Search on "Factory Pattern"

You can implement it kinda like this

Public Class MyClass
Private Sub New()
' You can not directly instantiate this class
End Sub

Public Shared Function GetInstance(param1 as string, param2 as integer,
....) as MyClass
Dim result as new MyClass 'Since its private, the constructor can be
called inside the class
''' Code to possibly load from database
If CanLoadFromDB then
Return result
Else
Return Nothing
End If
End Function

End Class

Instead of :
Dim objGribble as New cGribble()
If objGribble Is Nothing Then ...

You'll end up with:
Dim objGribble as cGribble = cGribble.GetInstance()
If objGribble Is Nothing Then ...

Now this will work. If you're totally set about this type of approach, then
go for it, dude! However, if you use the approach that Carl mentioned, you
do get one major benefit. All you know from this approach is that the class
can not be created. Was it because of a database error? Was it because of
a division Error? What about Solar Flares? If you throw an exception
inside of the constructor, you can catch it and inform the user about the
error, as it was thrown, as opposed to the assumption that it was error "X".
 
J

Jeff Carver

Thanks, Karl and David. These are very interesting approaches, and
they're definitely going into my snippet file! I'm not sure yet which
I'll use for this current project, but I imagine I'll be using them
both in different situations in the future.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top