Class construction

  • Thread starter Thread starter fredd00
  • Start date Start date
F

fredd00

Hi

I would like to create a class that could give me a null item from the
contructor.
let me explain

let's say i want a foo object of id 123 from the database

public foo(int 123)
{
// look in database
item found, assign values to private variables, return object
// not found
return null
}

I know you can't return some thing from the constructor how can this
be done.

my second option was to use a manager

foo f = fooManager.GetFoo(123);

the manager builds a foo object and check for a non empty foo object
if the object is empty return null other wise return foo object.

it works but it does not prevent people from calling foo(123) and
getting an empty object.

what is the best way to go about this

thanks
 
Hi

I would like to create a class that could give me a null item from the
contructor.
let me explain

let's say i want a foo object of id 123 from the database

public foo(int 123)
{
// look in database
item found, assign values to private variables, return object
// not found
return null

}

I know you can't return some thing from the constructor how can this
be done.

my second option was to use a manager

foo f = fooManager.GetFoo(123);

the manager builds a foo object and check for a non empty foo object
if the object is empty return null other wise return foo object.

it works but it does not prevent people from calling foo(123) and
getting an empty object.

what is the best way to go about this

thanks

Interesting,

One way might be to add a public static method to your Foo class
called

public static Foo CreateFoo(int i)

It would return what you desire, much like the "manager" class you
describe. The advantage of doing it this way is that you can now make
the Constructor to "Foo" private, thus only the CreateFoo method can
call it.

Cheers,
--Rob W
 
fredd00 said:
I would like to create a class that could give me a null item from the
contructor.

You can't. Use a static method instead:

public static Foo Find(int id)
{
return IdIsInDatabase() ? new Foo(id) : null;
}

(or something like that).

If you want to prevent people from calling the constructor directly,
just make it private.
 
Never occured to me before reading your question, but how about a ref or out
argument to the .ctor:

class T {
public T(ref object obj) { obj = null; }
};

It compiles, but I'm not sure how good an idea it is... I guess that's up to
you. HTH
 
Back
Top