Solved

Null references

Posted on 2003-12-03
9
569 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
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
 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

733 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