How to return null from c# class constructor after a validation?

S

Saravanan

Hi,

This may be a silly question. I would like to return null while creating a
new instance of a class and the validation inside the class constructor
fails.
For example:

class employee
{

public employee(int employeeid)
{
if(isemployeeexist(employeeid))
{
// validation success and proceed normally
}
else
{
// validation fails and needs to return null ?????
}
}
}

void main()
{
employee abc = new employee(1234);

if(abc == null)
{
....
}
}

How do i return null from a class constructor?

Any help will be much appreciated.

Thanks,
Saravanan.
 
J

Jon Skeet [C# MVP]

Saravanan said:
This may be a silly question. I would like to return null while creating a
new instance of a class and the validation inside the class constructor
fails.

You can't. Instead, write a static method which performs the validation
and then either returns the new instance or null.

An alternative is to make your constructor throw an exception.
 
S

Saravanan

Thanks for your response.

I got your alternatives by searching the net already. Though the
alternatives does the job, it doesn't look great atleast for me.

I guess i have no other choice than to stick with one of the alternatives.

cheers.
 
J

Jon Skeet [C# MVP]

Saravanan said:
Thanks for your response.

I got your alternatives by searching the net already. Though the
alternatives does the job, it doesn't look great atleast for me.

I guess i have no other choice than to stick with one of the alternatives.

Look at it from the other point of view - everywhere in the code where
you call a constructor, you can guarantee that if the constructor
returns, it *won't* return a null reference. Personally I like that a
lot :)
 
P

Peter Bromberg [C# MVP]

Getting a null reference from calling a class constructor is not (I don't
think) a logical or best-practices approach. Better to throw an exception
when you have a lot of business logic going on in the constructor. After all
the whole idea of having a constructor is to get back an instance of the
class, and getting a null reference gives us no information of any value at
all.
-- Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
Short Urls & more: http://ittyurl.net
 
L

Lasse Vågsæther Karlsen

Jon said:
Look at it from the other point of view - everywhere in the code where
you call a constructor, you can guarantee that if the constructor
returns, it *won't* return a null reference. Personally I like that a
lot :)

I agree with that, the explicit guarantee that if it doesn't throw an
exception, you got an instance reference, is a lot better than having to
check for null.

The original poster might argue that this would only be used with this
special class, but if the guarantee goes out the window (ie. the C#
compiler or .NET runtime would allow it), then it really is out the
window, special class or not.

But then I'm a proponent of the exception system as opposed to the
check-for-error-returncode system :)
 
A

Arne Vajhøj

Saravanan said:
This may be a silly question. I would like to return null while creating a
new instance of a class and the validation inside the class constructor
fails.
For example:

class employee
{

public employee(int employeeid)
{
if(isemployeeexist(employeeid))
{
// validation success and proceed normally
}
else
{
// validation fails and needs to return null ?????
}
}
}

void main()
{
employee abc = new employee(1234);

if(abc == null)
{
....
}
}

How do i return null from a class constructor?

As already stated then you don't.

The C# paradigm is to use exceptions.

If you really want to do it this way then:
- make the employee constructor do very little
- create a factory method that constructs an instance,
set properties and either return the instance
or return null depending on status

Arne
 
A

Arne Vajhøj

Peter said:
Getting a null reference from calling a class constructor is not (I don't
think) a logical or best-practices approach. Better to throw an exception
when you have a lot of business logic going on in the constructor. After all
the whole idea of having a constructor is to get back an instance of the
class, and getting a null reference gives us no information of any value at
all.

And in general there should not be so much bussines logic in
the constructor - it can easily become inflexible.

Arne
 
J

Jeff Louie

Saravanan... One approach is to use a static class factory to return a
reference of type employee by id. If an object of class Employee with
the given id already exist then the factory would return a reference to
the existing instance of class Employee. If an object of class Employee
with the given id did not exist, then factory could create a new
instance of Employee with the given id and return a reference to the new
instance OR the factory could throw an exception, etc.

Regards,
Jeff
 
V

vo1d

you could do it in this way:

public class Employee
{
private static Dictionary<int, Employee> _employeesTable = new
Dictionary<int, Employee>();
private readonly int _id;

public Employee(int id)
{
this._id = id;
}

public int Id
{
get
{
return (this._id);
}
}

public static Employee GetInstance(int id)
{
Employee returnInstance = null;
Employee._employeesTable.TryGetValue(id, out returnInstance);

//better would be
//if(!Employee._employeesTable.TryGetValue(id, out
returnInstance))
//{
// returnInstance = new Employee(id);
// Employee._employeesTable.Add(returnInstance._id,
returnInstance);
//}
return (returnInstance);
}
}

cheers
vo1d
 
J

Jeff Louie

vo1d... The "better method" looks like it needs a lock since it would
access a
static dictionary which makes me nervous. Perhaps I can entice John to
chime in
here about concurrent access to the static dictionary.

Regards,
Jeff
 
J

Jon Skeet [C# MVP]

Jeff Louie said:
vo1d... The "better method" looks like it needs a lock since it would
access a static dictionary which makes me nervous. Perhaps I can
entice John to chime in here about concurrent access to the static
dictionary.

Yes, it should indeed use a lock. Still a perfectly good approach, but
it does need some care on the thread-safety aspects :)
 
B

Ben Voigt [C++ MVP]

Jeff said:
vo1d... The "better method" looks like it needs a lock since it would
access a
static dictionary which makes me nervous. Perhaps I can entice John to
chime in
here about concurrent access to the static dictionary.

Unless the dictionary is totally immutable, both methods need a lock to be
thread-safe.
 

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