1

Long story short: I made a RequireNonDefaultAttribute (I mainly needed it for guids in my DTOs)

   [AttributeUsage(AttributeTargets.Property)]
    public class RequireNonDefaultAttribute : ValidationAttribute
    {
        public RequireNonDefaultAttribute()
            : base("The {0} field requires a non-default value.")
        {
        }

        public override bool IsValid(object value)
        {
            return !Equals(value, Activator.CreateInstance(value.GetType()));
        }
    }

and as the name states it's an attribute that requires the property in the DTO not to be the default of the current type. Everything was working fine. I thought why not use == instead of the Equals method. Since == is more C# style. So I transformed my code into

public override bool IsValid(object value)
            {
                return !(value == Activator.CreateInstance(value.GetType()));
            }

Anyway the expression always got evaluated to false. Can I get some explanation why does this happen?

john
  • 11
  • 1
  • There is nothing special about `IsValid` here, it's just that `==` for type `object` checks whether the two expressions refer to the same object, not whether two different objects hold the same value. The answers to the other question go into more detail. –  Aug 25 '18 at 12:50
  • @hvd So Guid is not a class it's a struct and `Equals` checks for values not if the references are the same except if overloaded... But I can see that there is an overfload `public static bool operator ==(Guid a, Guid b);` in the guid struct definition, so that doesn't explain why when comparing them using `==` it doesn't evaluate to `true` – john Aug 25 '18 at 13:02
  • Which version of `==` is used depends on the compile-time type of the expressions, not the run-time type. That's `object` in your case. –  Aug 25 '18 at 13:17
  • Because you've boxed your Guids to objects. `==` is resolved at compile time based on compile time types of the instances. In this case that is `object` where the `==` is reference equality. The Boxed structs are two separate instances (they are two separate boxes) so it fails. For example: `int x=3; Console.WriteLine((object)x == (object)x);` outputs false – pinkfloydx33 Aug 25 '18 at 13:20

0 Answers0