Where/How to instaniate an object to handle null reference exception C#
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Where/How to instaniate an object to handle null reference exception C#

  1. #1
    Join Date
    May 2013
    Posts
    1

    Where/How to instaniate an object to handle null reference exception C#

    Hey guys kind of a simple question, I'm not exactly sure where/how to initialize a new object instance so I don't get this error. I have a class object(Contact) that has another class object(ContactInfo) and sometimes the user decides not to input(instantiate) the ContactInfo object. So later when I try to do a search via Contact.ContactInfo, I get the error. Below I have the line of code where I get the error and then I have the two classes:
    foreach (var Contact in Contacts)
    {
    if (String.Equals(Contact._contactInfo.City.ToLower(), city, StringComparison.CurrentCulture))
    {
    ContactsByCity.Add(Contact);
    }
    }

    // and then the two classes:

    public class Contact : Person
    {
    private ContactInfo info;
    private ContactInfoLoader loader;
    public ContactInfo _contactInfo { get; set; }

    public Contact()
    { }
    public Contact(ContactInfo _info)
    {
    info = _info;
    }
    public ContactInfo GetContactInfo()
    {
    loader = new ContactInfoLoader(this);
    return loader.GatherContactInfo();
    }
    }
    public class ContactInfo
    {
    public string PhoneNumber { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set;}

    public ContactInfo()
    { }

    }

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    11,198

    Re: Where/How to instaniate an object to handle null reference exception C#

    Let me first make a comment about code conventions in C#. It's not your issue, but it helps other folks read your code. In C#, Pascal casing is used for method, property and Class names (e.g. ContactInfo) whereas camelCasing is used for local variables (such as the Contact variable in the foreach loop).

    Following those conventions, the foreach loop could be written as

    Code:
    foreach (var contact in Contacts)
     {
       if (String.Equals(contact._contactInfo.City.ToLower(), city, StringComparison.CurrentCulture))
       {
         ContactsByCity.Add(contact);
       }
    }
    So that makes it a bit more readable (as the PascalCase 'Contact' implies it's a class property or a class name). Not a big deal, but just easier to read.

    Now onto your problem. The problem is anytime you have a null object, you aren't going to be able to access any of its members. So if you can't prevent null objects from getting inserted into your code, you are going to have to guard against accessing null pointers.

    Code:
    foreach (var contact in Contacts)
    {
      if( contact != null )  // CHK1: this check is probably unnecessary unless you contact is a raw array (i.e. Contact[] Contacts)
      {
        if( contact._contactInfo != null ) // CHK2: check if the contactInfo field is not null
        {
          if(!String.IsNullOrEmpty(contact._contactInfo.City) // CHK3: check if the City string property is null
              && String.Equals(contact._contactInfo.City.ToLower(), city, StringComparison.CurrentCulture))
          {
            ContactsByCity.Add(contact);
          }
        }
      }    
    }
    So that should do it in terms of getting rid of the null reference exception.

    Now what you might want to do is to code the app in such a way to prevent the nulls from getting into the code.
    For CHK1, use a List<Contact> collection instead of a raw Contact[] array (if that's what you are doing). A List<> collection won't let you add a null entry, so any code that does a foreach on the collection could be made cleaner by not needing to check for null.
    For CHK2. Again when you create the Contact object, initialize its _contactInfo field so you never have to check it for null in consuming code.
    For CHK3. If you use an auto property (i.e. public string City { get; set; }) inside the class the property shouldn't be null as long as you don't set it to null. To avoid this problem, be sure to initialize any properties in the containing class when appropriate.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center