Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a compact way of telling the C# compiler to use the base Equals and == operator?

I am fairly new to C#, and I come from a C++ background.

I have defined a struct, and the (Microsoft) compiler keeps popping up the error CA1815 "'GenericSendRequest' should override Equals"

I read a bit around and saw that C# structs derive from ValueType which impleents a generic Equals using reflection. This confused me more:

  1. Why does the compiler create an error instead of a warning if its just a performance issue?
  2. Why does it define that generic Equals in the first place if it's not going to let you use it?

So how can I tell the compiler that "I don't care"? Something similar with just declaring assignment operator in a C++ class without providing definition to acknowledge that I know what I am doing.

So far my solution has been to include:

    public static bool operator ==(GenericSendRequest lhs, GenericSendRequest rhs)
    {
        return lhs.Equals(rhs);
    }

    public static bool operator !=(GenericSendRequest lhs, GenericSendRequest rhs)
    {
        return !lhs.Equals(rhs);
    }

    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }

    //Yes, it also makes me override GetHashCode since I'm overriding Equals.
    public override int GetHashCode()
    {
        return base.GetHashCode();
    }

in my struct, which is just awful.

Edit: This is the struct definition:

public struct GenericSendRequest
{
        public LiveUser             Sender;
        public LiveUser[]           Receivers;
        public Message              Msg;
        public ServiceHttpRequest   HttpRequest;
}

Its usage is just multiple return values from a function:

public static GenericSendRequest CreateGenericSendRequest(...);
like image 590
Ramon Zarazua B. Avatar asked Feb 02 '23 13:02

Ramon Zarazua B.


1 Answers

This is definitely not an error, its only a warning - and that warning even only will show up if you have enabled code analysis as part of your build. It's a suggestion for performance optimization - take it that way.

Edit:

Turns out this is configurable:

Go to Project Properties | Code Analysis | Run this rule set.. Open

Expand the Performance section - for CA 1815 you can select whether you want this to be a warning, an error or none.

enter image description here

like image 138
BrokenGlass Avatar answered Feb 05 '23 03:02

BrokenGlass