Solved

Null references

Posted on 2003-12-03
9
563 Views
Last Modified: 2010-04-16
I have created a C# class for use in a program.  In this class, I have overloaded the equals operator so that it compares the Name property of the class to declare equality.  The problem comes in when I then try to determine if an instance of that class is null.  The execution is passed to the overloaded equals function, but since one or both sides is null, then a System.NullReferenceException is thrown.  I am currently currently using the following method as a workaround, but I know there has to be a better way to handle this:
public static bool operator==(ConfigSection left, ConfigSection right)
{
                 try
      {
            if((left.Name == right.Name) && (left.Type == right.Type))
                  return true;
      }
      catch(System.NullReferenceException nr)
      {
            return true;
      }

      return false;
}

Can anyone tell me a better way to do this?
0
Comment
Question by:dirtdart
9 Comments
 
LVL 2

Expert Comment

by:smitty22
ID: 9867020
What if you test for null in an if statement, before you test the Name and Type properties?

If one of the objs is null, but the other one is not, then the objs are obviously not equal, so return false.  I would probably also return false in the case where both objs are null.


public static bool operator ==( ConfigSection left, ConfigSection right ) {
  if ( left == null || right == null ) {
    return false;
  }

  return left.Name == right.Name && left.Type == right.Type;
}
0
 
LVL 5

Author Comment

by:dirtdart
ID: 9867051
I tried that.  It calls the overloaded equals operator again, which performs the test again, which calls the equals operator again...  And eventually leads to a stack overflow.
0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 9867194
then it would appear that your best choice is your first approach---catch the NullException when it occurs.

but rather than returning 'true' on the NullException (as your code now does), return 'false', or are you allowing null to equal ANYTHING.  Seems that null should equal NOTHING, hence a null should always trigger a false return.

AW
0
 
LVL 5

Author Comment

by:dirtdart
ID: 9867233
The reason I am having the exception return true is the following code:

if(cs == null)

This will enter the overloaded operator.  If either side is null, it will throw an exception.  This doesn't return the correct response, but if I were to return false, then I would never know if the object were equal to null.  The more I think about it, I'm beginning to think that my best option is going to be not comparing it to null at all, but simply trying to use the object and catching the System.NullReferenceException caused by that.  Anyone with any other suggestions?
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 9

Accepted Solution

by:
tinchos earned 500 total points
ID: 9868045
Hi dirtdart

I'm not sure about what you're trying to do, but what is happening to you once happened to me and that's because I'm going to tell you the following.........

Generally, you do not override operator==, as if you do that, you'll have the problem you're having.........

Instead you override the equals method which is the one used to compare objects. So in your case you'll have to

implement equals method to the ConfigSection class with


public bool equals( ConfigSection otherSection )
{
     if( otherSection != null )
     {
          return this.Name.equals( otherSection.Name ) && this.Type.equals( otherSection.Type );
     }

      // If the other one is null, then they are different
      return false;
}

Note: This piece of code is considering that both name and type are objects that have the equal method implemented.

then you can make

ConfigSection section1, section2;

// Your code here

if( section1.equals( section2 ) )
{
}


Hope this helps

Tincho
0
 
LVL 5

Author Comment

by:dirtdart
ID: 9868073
Thanks.  That wasn't what I was hoping for, but it's definately the right answer.  I guess that's one of the few spots where I still favor C++ over C#.
0
 
LVL 9

Expert Comment

by:tinchos
ID: 9868089
Yeap, that happens very often.........

I felt the same way you're feeling now after 5 hours trying to figure out how I could solve it.

Cheers

Tincho
0
 

Expert Comment

by:valentint
ID: 9870517
- Use the static Equals method of Object() to check for equality of both references and to check for equality to null
- of course you should also overload!= operator

class ConfigSection
{
string name;

            public static bool operator == (ConfigSection left, ConfigSection right)
            {
                  if(Object.Equals(left,right))
                        return true;

                  if(Object.Equals(left,null) || Object.Equals(right,null))
                        return false;
                  return left.name.Equals(right.name);
            }

            public static bool operator != (ConfigSection left, ConfigSection right)
            {
                  return !(left == right);
            }

            public ConfigSection(string s)
            {
                  name = s;
            }
      }
0
 
LVL 5

Author Comment

by:dirtdart
ID: 9873896
That's great, valentint!  As easy as C# is, I still seem to have quite a bit of learning to do.  I'll post another question to award you points, because that's exactly what I was looking for.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now