Does type check for correct choice instead of zero?

One of my (senior) employees is doing something really strange in his code.

Instead of checking the variable for null, it checks the type. And since

null is FooType

really returns false, this works.

public class Foo
{
    private string _bar = null;

    public string Bar
    {
        get
        {
            // strange way to check for null
            return (_bar is string) ? _bar : "";
        }
        set { _bar = value; }
    }
}

I think this is bad coding, and it seems Resharper agrees with me. Is there a reason to write a check this way?

Is this a valid way to check for a variable? Or can it be considered bad style or maybe even harmful in some special cases?

I do not want to confront him, if I'm not sure that this really does not make sense.

+5
source share
4 answers

This is not good. Best would be simple:

return _bar ?? string.Empty;

, , ? , . , "is" , null, false. , .

+10

, . _bar string, .

+3

, . :

return _bar ?? "" ;

- , :

public class DefaultableValue<T>
{
    private T m_Value = default(T);
    public T Value
    {
        get
        {
            if (IsInvalidPredicate(m_Value))
            {
                m_Value = IfDefaultValueFunc();
            }
            return m_Value;
        }
    }
    private Predicate<T> IsInvalidPredicate { get; set; }
    private Func<T> IfDefaultValueFunc { get; set; }
    public static implicit operator T(DefaultableValue<T> property)
    {
        return property.Value;
    }
    public DefaultableValue(Predicate<T> isInvalidPredicate,Func<T> ifDefaultFunc)
        : this(default(T), isInvalidPredicate, ifDefaultFunc)
    {
    }
    public DefaultableValue(T initValue, Predicate<T> isInvalidPredicate, Func<T> ifDefaultFunc)
    {
        this.m_Value = initValue;
        this.IsInvalidPredicate = isInvalidPredicate;
        this.IfDefaultValueFunc = ifDefaultFunc;
    }
}

class Test
{
    DefaultableValue<string> AString { get; set; }

    public Test(string initialValue)
    {
        this.AString = new DefaultableValue<string>(initialValue, 
            (value) => string.IsNullOrWhiteSpace(value),
            () => string.Empty);
    }
}

....
var test = new Test(null);
var someString = test.AString; // = "" not null
+3

if the public property declared above returned objectinstead string, it could make sense. However, since it returns a string, this type of check does not make sense. If you want to return an empty string, you can do something like this:

public class Foo 
{ 
    private string _bar = null; 

    public string Bar 
    { 
        get 
        {  
            return (String.IsNullOrWhitespace(_bar)) ? "": _bar; 
        } 
        set { _bar = value; } 
    } 
} 
0
source

All Articles