I am trying to compare two structs using equals (==) in C#. My struct is below:
public struct CisSettings : IEquatable<CisSettings>
{
public int Gain { get; private set; }
public int Offset { get; private set; }
public int Bright { get; private set; }
public int Contrast { get; private set; }
public CisSettings(int gain, int offset, int bright, int contrast) : this()
{
Gain = gain;
Offset = offset;
Bright = bright;
Contrast = contrast;
}
public bool Equals(CisSettings other)
{
return Equals(other, this);
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
var objectToCompareWith = (CisSettings) obj;
return objectToCompareWith.Bright == Bright && objectToCompareWith.Contrast == Contrast &&
objectToCompareWith.Gain == Gain && objectToCompareWith.Offset == Offset;
}
public override int GetHashCode()
{
var calculation = Gain + Offset + Bright + Contrast;
return calculation.GetHashCode();
}
}
I am trying to have struct as a property in my class, and want to check to see if the struct is equal to the value I am trying to assign it to, before I go ahead and do so, so I am not indicating the property has changed when it hasn't, like so:
public CisSettings TopCisSettings
{
get { return _topCisSettings; }
set
{
if (_topCisSettings == value)
{
return;
}
_topCisSettings = value;
OnPropertyChanged("TopCisSettings");
}
}
However, on the line where I check for equality, I get this error:
Operator '==' cannot be applied to operands of type 'CisSettings' and 'CisSettings'
I can't figure out why this is happening, could somebody point me in the right direction?
Equals()
? – Electrochemistryif (obj == null || GetType() != obj.GetType())
is a very strange way to writeif(!(obj is CisSettings))
. – JohnyEquals(CisSettings)
and haveEquals(object)
call it, rather than the other way around. – JohnyGetHashCode
on a 32 bit integer is unnecessary; a 32 bit integer is its own hash code. – Johnyif (obj == null || GetType() != obj.GetType())
is a very strange way to writeif(!(obj is CisSettings))
Sure, it looks like he's imitating the preferred way to doEquals
with non-sealed classes. There it is good practice to check if eitherthis
orother
is more derived. But of course with a sealed type, like a struct in this case, there's no need for that. – Scruggs==
and!=
. But I think it's more important to answer this question: why doesn'tstruct
implementation==
and!=
by default, using the already implementedEquals()
– Echelon