Why is an interface needed?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • junki

    Why is an interface needed?

    Code:
    interface IEquatable<T>
    {
        bool Equals(T obj);
    }
    public class Car : IEquatable<Car>
    {
        public string Make {get; set;}
        public string Model { get; set; }
        public string Year { get; set; }
    
        // Implementation of IEquatable<T> interface
        public bool Equals(Car car)
        {
            if (this.Make == car.Make &&
                this.Model == car.Model &&
                this.Year == car.Year)
            {
                return true;
            }
            else
                return false;
        }
    }
    I think the above code does not need interface . i understand how to use interface but i don't understand why use interface.pleas e tell me the different between using interface and not using.
    Last edited by Curtis Rutland; Oct 13 '10, 04:43 PM. Reason: Please use [CODE] tags when posting code.
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    Interfaces provide a means of defining common functionality that may be expected by other classes or functions. In this case, inheriting from the IEquitable interface ensures the Equals method is available.

    I don't know the rest of your code, but perhaps something requires that method? Though I do see that this interface is defined with your code, so I don't know... it's obviously not using the .NET version of it (which might even be in IComparable, not sure).

    Perhaps this code is just an example? I can't really speculate further without knowing the context.

    If you want a better example of when to use an interface, check out my QuadTree insight. I require an interface on whatever goes into the quad tree so I can ensure it has the Rect property.



    I hope that helps!

    Comment

    • mldisibio
      Recognized Expert New Member
      • Sep 2008
      • 191

      #3
      In this particular case, IEquatable<Car> is not so much for your own use as for use by Framework collections. If all you will ever do is compare to Cars for equality in your own code, you could just write an equals method. You could even name it something like IsSameMakeAndMo del().
      But the real point is that if you have a HashSet or other collection which guarantees that each item in the collection will be unique, that collection does not know anything about Car, even if it has an Equals method. Rather, the collection looks at the item and asks "Do you implement IEquatable? Because if you do, no matter what you are, I know you will have an Equals() method I can call in order to guarantee that each item I manage is unique."

      Comment

      Working...