c# - Check for 'null' on value and reference types -
i'm little confused checking 'null' (empty, not available, without value) on value , or reference types. there seem lot of possible ways , of them used.
let's i've got following extension method can used somehow similar maybe monad:
public static tresult usewith<t, tresult>(this t value, func<t, tresult> action) { // if value not null // execute action // else return default value of 'tresult' }
so? how check null?
if(value != null)
or (which checks null on reference types, default on value types)
if(!equals(value, default(t))
or
if(!equalitycomparer<t>.default.equals(value, default(t))
or (with precheck)
if (!typeof(t).isvaluetype) { if (equals(source, default(t))) return tresult; }
or better create 2 methods restrictions?
public static tresult usewith<t, tresult>(this t value, func<t, tresult> action) t : class { if(value == null) public static tresult usewith<t, tresult>(this t value, func<t, tresult> action) t : struct { if(value.hasvalue)
the pseudocode in first snippet work want to. variable typed unbounded generic argument can compared null
using ==
operator. code compile, , evaluate false
whenever t
non-nullable value type.
you don't want compare t
default value, because default value may not null
.
there no need explicitly check if t
value type, or have separate overloads reference/value types, ==
operator handles when it's jitted.
Comments
Post a Comment