0

I have a generic function(object, object), one of parameters can be new() when I try to compare object to new() it is always false.

public static void TestFunction<T>(object requestData, object storedData) where T : class, new()
{
    if (requestData != null && storedData != null)
        if (requestData?.GetType().Name != storedData?.GetType().Name)
        { throw new Exception("object types are not match"); return; }
    if (requestData == null) throw new Exception("request can not be null");

    ```
    //storedData might be new T()
    // but even i am creating new objects to compare inside function - no luck
    ```

    object o = (T)Activator.CreateInstance(typeof(T));
    object o1 = (T)Activator.CreateInstance(typeof(T));
    object o2 = new T();

    T test = new T();

    ```//all return false
    o.Equals(o1).Dump();
    test.Equals(new T()).Dump();
    o2.Equals(o).Dump();

}

I expect the comparison to be true.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Power Mouse
  • 727
  • 6
  • 16
  • 2
    They're two different references, so they're always going to compare false unless T is a value type. To solve the problem, implement `IEquatable` on your classes. Then, when you call `Equals()`, it will do what you expect it to. – Robert Harvey May 10 '19 at 15:20
  • @HereticMonkey: That post discusses `==`, which is not being used here. – Robert Harvey May 10 '19 at 15:23
  • thank you. i found solution as described in [article](https://stackoverflow.com/questions/506096/comparing-object-properties-in-c-sharp): – Power Mouse May 10 '19 at 16:17

1 Answers1

1

Default object comparisons are always by reference pointer. new T() is always going to have a new reference.

Steve Todd
  • 1,250
  • 6
  • 13