C # IsNullOrZero

This pattern is very common in my code:

x= x== 0? 1: x;
x= x==null? 1: x;


However, it happens that sometimes x is a long expression and I have to use intermediate variables. It's just useless boilerplate code. I can prepare a method and call it instead:

Util.IfNullOrZero(x, 1);


But that's just ugly. What is the best way to express a picture? Ruby has a syntax like this for when x is nil , which gets rid of redundant x's:

x||= 1


I could expand object

in a way

public static class wtf
    public static T Default<T>(this object o, T d)
        return o == null ? d : new object[] { o }.Cast<T>().First();


And then do

object param= null;
int x= param.Default(1);


But this is a little expensive.

In short, what is the best way to make C # do x || = 1 like in ruby?


This is what I have prepared. I am currently looking for a faster way to use the Template parameter to convert an object to T.

public static class MyExtensions
    public static T d<T>(this object o, T d)
        return o == null || o.Equals(default(T)) ? d : new object[] { o }.Cast<T>().First();


In fact, the code does three things at once: the Casts to default type, checks for the default, and also checks for null.

Update 2

return o == null || o.Equals(default(T)) ? d : (T)o; // much simpler and faster


I still think this is a common situation that should be included in the main language.

Update 3 This is what I finally wrote, given the DataTable types DBNull.

public static T d<T>(this object o, T d)
    return o == null || (o is System.DBNull) || o.Equals(default(T)) ? d : (T)Convert.ChangeType(o, typeof(T));



source to share

4 answers

To test null

and provide a default value, you can use the operator ??


return x ?? new Foo();


This means that if x

there is null

, return new Foo()

, else return x

. You can use it for reference and nullable types. For nune-nullable types like int

, you still need to check explicitly 0




To handle the "== null" case, the null coalesce operator does the trick.

y = x ?? z;



if (x == null)
    y = z;
    y = x;


I am not aware of anything that checks for both null and null values, writing a method to do this might be the best solution. Here it is:

public static T IsNullOrZero<T>(this T variable, T defaultValue)
            // defaultValue can't be null, doesn't make sense
            if (defaultValue == null) throw new ArgumentException("default value can't be null", "defaultValue");
            if (variable == null || variable.Equals(default(T))) 
                return defaultValue;
            return variable;



x = x.IsNullOrZero(y);


Note: this actually works with non-numbers as well (the name can be misleading when dealing with non-numbers ... maybe something like strings IsNullOrDefault

might be a better name).



You can check how

public static bool IsNullOrValue(this int? value, int valueToCheck)
    return (value??valueToCheck) == valueToCheck; 


more details here



What you need is the Coalesce operator (??), which does exactly that - if it returns the first operand if it is not null, and the second if it is. This will create a new object if the current one is null:

return myObj ?? new MyObject();


Note that the operator only works for classes and reference types, not for int and other value types that cannot be null. There you will need to manually check for defaults, uninitialized values ​​(0 for ints and shorts and stuff, false for bools, etc.)



All Articles