Note that there are some explanatory texts on larger screens.

plurals
  1. POC# IsNullOrZero
    primarykey
    data
    text
    <p>This pattern comes up very frequently in my code:</p> <pre><code>x= x== 0? 1: x; //or x= x==null? 1: x; </code></pre> <p>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: </p> <pre><code>Util.IfNullOrZero(x, 1); </code></pre> <p>But that's just ugly. What is the best way of expressing the pattern? In ruby there is such syntax for <strong>when x is nil</strong> which gets rid of redundant x's:</p> <pre><code>x||= 1 </code></pre> <p>I could extend <code>object</code> in a manner </p> <pre><code>public static class wtf { public static T Default&lt;T&gt;(this object o, T d) { return o == null ? d : new object[] { o }.Cast&lt;T&gt;().First(); } } </code></pre> <p>And then do </p> <pre><code>object param= null; int x= param.Default(1); </code></pre> <p>But that's a bit expensive. </p> <p>In short how to best make C# do x||= 1 like in ruby?</p> <p><strong>Update</strong></p> <p>This is what I cooked up. I'm currently looking for a faster way of using the Template parameter to convert object to T.</p> <pre><code>public static class MyExtensions { public static T d&lt;T&gt;(this object o, T d) { return o == null || o.Equals(default(T)) ? d : new object[] { o }.Cast&lt;T&gt;().First(); } } </code></pre> <p>In fact the code does three things at once: Casts to default type, checks for default value and also checks for null. </p> <p><strong>Update 2</strong></p> <pre><code>return o == null || o.Equals(default(T)) ? d : (T)o; // much simpler and faster </code></pre> <p>I still think it is a commonality which needs to be included in core language.</p> <p><strong>Update 3</strong> This is what I finally wrote, taking into account DataTable DBNull types.</p> <pre><code>public static T d&lt;T&gt;(this object o, T d) { return o == null || (o is System.DBNull) || o.Equals(default(T)) ? d : (T)Convert.ChangeType(o, typeof(T)); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload