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:
- Why does the compiler create an error instead of a warning if its just a performance issue?
- 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(...);
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..OpenExpand the
Performancesection – for CA 1815 you can select whether you want this to be a warning, an error or none.