1

Is there a support in C# 4.0 to do that in one line?

I did for objects:

 if (ReferenceEquals(null, myDynamicVar))

so now I need to see if this a zero. how to do it and is there a statement that can do both?

Amiram Korach
  • 13,056
  • 3
  • 28
  • 30
user1025852
  • 2,684
  • 11
  • 36
  • 58
  • 2
    Why do you think a `ValueType` is always zero? `bool` for example is `false` (this is not zero). See here: http://stackoverflow.com/questions/325426/programmatic-equivalent-of-defaulttype – Amiram Korach Aug 15 '12 at 14:13

3 Answers3

4
if (ReferenceEquals(null, myDynamicVar) || Equals(0, myDynamicVar)) ...
Tim Rogers
  • 21,297
  • 6
  • 52
  • 68
3
public bool IsDefault<T>(T value)
{
    if(value == null) return true;
    return value.Equals(default(T));
}

int v = 5;
object o = null;
IsDefault(v); //False
IsDefault(0); //True
IsDefault(o); //True
IsDefault("ty"); //False
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
  • 1
    Unfortunately, if `o` was type dynamic, like in the question, this code would not work. – jbtule Aug 15 '12 at 14:51
  • you can try to call it IsDefault(o) and it will work. The case is that it will return false if dynamic o = 0; That's why you shouldn't use dynamic is it is unnecessary. – Ilya Ivanov Aug 15 '12 at 15:02
  • the case of Tim Rogers won't work if dynamic o = DateTime.MinValue – Ilya Ivanov Aug 15 '12 at 15:04
  • Actually all you need to make yours work for every case is an overload `public bool IsDefault(object value) { return (value == null); }` The dynamic binder would choose the generic form except when it's null and then it would choose the object version. – jbtule Aug 15 '12 at 16:21
2

Sloppy:

if (ReferenceEquals(null, myDynamicVar) || myDynamicVar ==
   (myDynamicVar.GetType().IsValueType ? Activator.CreateInstance(myDynamicVar.GetType()) : null)
{
    //Code greatness
}

Cleaner:

    public static bool IsDefault(dynamic input)
    {
        if (input == null)
        {
            return true;
        }
        else if (input.GetType().IsValueType)
        {
            return input == Activator.CreateInstance(input.GetType());
        }
        else
        {
            return false;
        }
    }
Jaime Torres
  • 10,365
  • 1
  • 48
  • 56