Null references

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?
LVL 5
dirtdartAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

smitty22Commented:
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
dirtdartAuthor Commented:
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
Arthur_WoodCommented:
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
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

dirtdartAuthor Commented:
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
tinchosCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dirtdartAuthor Commented:
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
tinchosCommented:
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
valentintCommented:
- 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
dirtdartAuthor Commented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.