Question about checking null values

I just discussed with one of my colleagues about checking for null values.

It is SWEARS that β€œin certain situations” the code below would give it an exception with a null value:

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

}

but when changing the code there will be no errors:

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

}

I told him that this could not be, but he swears that he corrected his code. Is there a possible situation where the above change can fix the error?

+3
source share
4 answers

Not with a string, no. You could do it with poorly written overload ==:

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);
}

, ! , - , - . , , . , , ( , ) , .

+12

, " " C/++, "=" "==" :

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

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

# .

+6

. ==, .

+2

if (test == null), , . .

+1

Source: https://habr.com/ru/post/1758272/


All Articles