I'll try to be as simple as possible:
This is what you are doing:
if ( <intValue>.CompareTo(<IData object>) == 0 )
{ (...) }
This is what you need:
if ( <intValue>.CompareTo(<int value>) == 0 )
{ (...) }
Now, here is how you can do it (very simplistic way):
public bool EqualsTo(IData otherData)
{
if(_data.CompareTo(otherData._data) == 0)
return true;
return false;
}
This is another way to achieve the same (which I'd use for your scenario):
public interface IData : IEquatable<IData> { }
public class IntegerData : IData
{
// The value will be private for this example
// Could be public int Value { get; private set; }
private int Value { get; set; }
// Constructor
public IntegerData(int value) { Value = value; }
// Implements Equals (from IEquatable - IData)
public bool Equals(IData other)
{ return Value.Equals(other.Value); }
}
And this is another solution for the same task:
- Remember that this is a bigger solution for a somewhat small problem. This could lead to bigger classes and bigger problems so use it only if you need it. Be simple. Keep simple. Don't get into something too complex because you'll have to maintain that code over time...
- Also keep in mind that I've used the default "GetHashCode" method. Sometimes that's enough but keep in mind that you might need to create/use a custom hash algorithm depending on your need.
- Finally consider that this is just an example. I've created the interfaced based on Gabe's answer but added a method just for the hash itself. You might want to remove or improve. Consider your needs.
// An interface that is based on IEquatable for better compatibility but also
// enables you to create a diferent EqualsTo method...
public interface IData<T> : IEquatable<T>
{
T GetData();
int GetDataHash();
bool EqualsTo(IData<T> other);
}
// One class (string)
public class StringData : IData<string>
{
private string Value { get; set; }
public StringData(string value) { Value = value; }
public string GetData() { return Value; }
public int GetDataHash() { return GetData().GetHashCode(); }
// From IEquatable
public bool Equals(string other)
{ return Value.Equals(other); }
// From IData (customized to compare the hash from raw value)
public bool EqualsTo(IData<string> other)
{ return GetDataHash() == other.GetDataHash(); }
}
// Another class (int)
public class IntData : IData<int>
{
private int Value { get; set; }
public IntData(int value) { Value = value; }
public int GetData() { return Value; }
public int GetDataHash() { return GetData().GetHashCode(); }
// Again from IEquatable
public bool Equals(int other)
{ return Value == other; }
// Again from IData (customized to compare just the hash code)
public bool EqualsTo(IData<int> other)
{ return GetDataHash() == other.GetDataHash(); }
}