[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Null references

Posted on 2003-12-03
9
Medium Priority
?
573 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Suggested Courses

656 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