开发者

Question about checking for null values

I just got into a debate with one of my coworkers about checking for null values.

He SWEARS that "in certain situations" the code below would give him a null value exception:

string test = null;
if(test == null) //error here
{

}

but that if changed the code to this there would be no error:

str开发者_JS百科ing test = null;
if(null == test) //NO error here
{

}

I told him there was no way this could happen but he swears it fixed his code. Is there any possible situation where the above change could fix an error?


Not with string, no. You could do so with a badly written == overload though:

using System;

public class NaughtyType
{
    public override int GetHashCode()
    {
        return 0;
    }

    public override bool Equals(object other)
    {
        return true;
    }

    public static bool operator ==(NaughtyType first, NaughtyType second)
    {
        return first.Equals(second);
    }

    public static bool operator !=(NaughtyType first, NaughtyType second)
    {
        return !first.Equals(second);
    }
}

public class Test
{    
    static void Main()
    {
        NaughtyType nt = null;
        if (nt == null)
        {
            Console.WriteLine("Hmm...");
        }
    }
}

Of course, if you changed the equality operator to this:

public static bool operator ==(NaughtyType first, NaughtyType second)
{
    return second.Equals(first);
}

then your colleagues code would fail, but yours wouldn't! Basically if you overload operators properly - or use types which don't overload operators - this isn't a problem. If your colleague keeps claiming he's run into it, ask him to reproduce it. He certainly shouldn't be asking you to reduce readability (I believe most people find the first form more readable) on the basis of something he can't demonstrate.


I think this is a left-over from a 'best practice' in C/C++, because using '=' instead of '==' is an easy to make mistake:

if(test = null)  // C compiler Warns, but evaluates always to false

if(null = test)  // C compiler error, null cannot be assigned to 

In C#, they both produce an error.


You're right. If he can reproduce this without an overloaded == operator, invite him to post it here.


The test of if (test == null) if test is a string is valid and will never give an exception. Both tests are also essentially exactly the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜