-2

I've a piece of code that has currentValue of type object.

object currentValue = 0;

bool result = object.Equals(currentValue, default);

I would expect the result to be true because 0 is a default value.

This is also not true

object.Equals(0, default);

Even this is not true

Int32.Equals(0, default);

My question is how to check if a boxed value is a default value.

I guess this should be done:

Type type = currentValue?.GetType();
object.Equals
(
    currentValue, 
    type != null && type.IsValueType 
    ? 
    Activator.CreateInstance(type) 
    : 
    null
);
Wouter
  • 2,540
  • 19
  • 31

2 Answers2

3

Isn't default always null?

No. It is not. default for int is 0 (boxing happens in this case), for example. But it is null for an object. Some examples, and explanations.

1

Your object.Equals(currentValue, default); returns false; the int is 0, the default for object is null, so your code asks object.Equals(0, null);, which is false. C# isn't going to go "well, the object in arg1 is an int, so the default in arg2 should be the default for int, which is 0".. It's just going to go "arg2 is an object, the default for object is null, arg2 is null". If you want the arg2 to be an int, and have a default of 0, then pass the type in brackets after the default. It will be boxed up as an object when it's passed into Equals, just like the first argument is, but specifying default(int) will stop the compiler from inferring "you mean default for object because arg2 is object"

object.Equals(currentValue, default(int)); //or Int32

Whether this is "correct" or not isn't currently answerable - asking us that is like asking "does this code do what I want?" - you didn't tell us what you want, so we can't say, but it feels like you're trying to find a way of testing whether an object is the default value for a type.. In which case comparing the default for int to the default for object isn't correct. You need to be mindful of what the compiler will interpret you mean when you say default - it'll use its best guess of what type to use from the surrounding context if you aren't explicit

The following might be a more compact/readable way of achieving the the same ends (assuming the goal is to determine if the value of currentValue is the default for an int):

if((int)currentValue == default)

In this case the compiler will infer the type of default it will use from the type of (int)currentValue, but you need to know that currentValue is an int so you can do the cast. You can't keep currentValue as object and compare to default(int) because there isn't an operator overload of == for object and int. You're probably thus down to this rephrasing of the original, but currentValue cannot be null:

 if(currentValue.Equals(default(int)))
Caius Jard
  • 72,509
  • 5
  • 49
  • 80