One of my (senior) coworkers does something really strange in his code.
Instead of checking a variable for null, he checks for the type. And because
null is FooType
actually 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 Resharper seems to agree with me. Is there any reason to write the check this way?
Is this a valid way to check the variable? Or can this be considered bad style or maybe even harmful in some special cases?
I don’t want to confront him unless I am sure that this actually does not make sense.
This is not a good way. A better way would be to just:
Is it clear when you read your colleagues code that he is looking for nulls? No, then it isn’t a good choice. Probably what the “is” operator will do first is just check for null and then return false. So it becomes much cleaner to just do that yourself. Or just use the null-coalescing operator