Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / March 2008

Tip: Looking for answers? Try searching our database.

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

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Saravanan - 20 Mar 2008 17:10 GMT
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.
Jon Skeet [C# MVP] - 20 Mar 2008 17:15 GMT
> 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.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Saravanan - 20 Mar 2008 17:40 GMT
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.

> > 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
[quoted text clipped - 4 lines]
>
> An alternative is to make your constructor throw an exception.
Jon Skeet [C# MVP] - 20 Mar 2008 17:45 GMT
> 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 :)

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Lasse Vågsæther Karlsen - 22 Mar 2008 10:56 GMT
>> Thanks for your response.
>>
[quoted text clipped - 7 lines]
> 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 :)

Signature

Lasse Vågsæther Karlsen
mailto:lasse@vkarlsen.no
http://presentationmode.blogspot.com/
PGP KeyID: 0xBCDEA2E3

Peter Bromberg [C# MVP] - 20 Mar 2008 21:08 GMT
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

> Hi,
>
[quoted text clipped - 35 lines]
> Thanks,
> Saravanan.
Arne Vajhøj - 24 Mar 2008 03:09 GMT
> 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
Arne Vajhøj - 24 Mar 2008 03:08 GMT
> 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
[quoted text clipped - 28 lines]
>
> 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
vo1d - 24 Mar 2008 19:24 GMT
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

>> 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
[quoted text clipped - 37 lines]
>
> Arne
Jeff Louie - 24 Mar 2008 21:24 GMT
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
Jon Skeet [C# MVP] - 24 Mar 2008 22:48 GMT
> 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 :)

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Ben Voigt [C++ MVP] - 24 Mar 2008 23:03 GMT
> 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.

> Regards,
> Jeff
>
> *** Sent via Developersdex http://www.developersdex.com ***
Jeff Louie - 24 Mar 2008 07:02 GMT
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

Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.