Object Construction

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

First, just want to say that I just got here to c# from Visual Fox Pro and am
enjoying learning a new language.

Here is my question: What is the best way to handle the situation whereby
an object gets created by some client code, but for some reason that object
cannot be created. How do you notify the client code that Foo is null and
should not be used?

Here is a code example:

public class Foo()
{
Foo()
{
// Do stuff here that could fail, such as a database is not available.
}
public DoStuff();
}

public class Form1{

FooObj = new Foo();
Form1() {
FooObj.DoStuff();
//The above fails because Foo could not be created properly.
}

}

I am wondering what the best practice is for C#. In VFP, I would check for
the existence of the object (ie it is not null) before using it.
 
Hi

I belive one of the best practices is to use a factory class. In a call to
the method that creates your object you are able to set return value to null
or throw an exception. Throwing exeptions in constructor can sometimes cause
some complications.
 
Back
Top