3

This pattern comes up very frequently in my code:

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

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

Util.IfNullOrZero(x, 1);

But that's just ugly. What is the best way of expressing the pattern? In ruby there is such syntax for when x is nil which gets rid of redundant x's:

x||= 1

I could extend object in a manner

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 that's a bit expensive.

In short how to best make C# do x||= 1 like in ruby?

Update

This is what I cooked up. I'm currently looking for a faster way of using the Template parameter to convert 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: Casts to default type, checks for default value and also checks for null.

Update 2

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

I still think it is a commonality which needs to be included in core language.

Update 3 This is what I finally wrote, taking into account DataTable DBNull types.

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

4 Answers 4

4

For handling the "==null" case, the null coalesce operator does the trick.

y = x ?? z;

means

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

I'm not aware of something that check for both zero and null, writing a method to perform this task might be the best solution. Here it goes:

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

Usage:

x = x.IsNullOrZero(y);

Note: this in fact works on non-numbers too (name might be misleading if dealing with non-numbers... maybe something along the lines of IsNullOrDefault might be a better name).

1
  • In fact, I grew fond of the idea and added this method to my "toolbox" project.
    – Alex
    Mar 9, 2012 at 7:50
3

You can check like

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

more on here

1
  • What about other numeric types ? This also does't handle the case when value is 0...
    – Alex
    Mar 8, 2012 at 8:47
2

For checking for null and providing a default value, you can use the ?? operator:

return x ?? new Foo();

That means, if x is null, return new Foo(), else return x. You can use it for reference types and nullable types. For nun-nullable types like int, you still need to explicitly check for 0.

0

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

return myObj ?? new MyObject();

Note that the ?? operator works only for classes and reference types, not for ints and other value types that can't be null. There, you'll have to check manually for default, uninitialized values (0 for ints and shorts and stuff, false for bools, and so forth)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.