Class construction

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
 
R

Rob Whiteside

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
 
J

Jon Skeet [C# MVP]

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.
 
G

Guest

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
 

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

Top