Skip to content

Interfaces

Mario Gutierrez edited this page Jan 7, 2017 · 2 revisions

C# interfaces are similar to Java interfaces.

public interface IClashing
{
  public void ClashingMethod();
}

If by chance you have methods in different interfaces that clash, you can define them explicitly.

class SomeClass : IClashing, IAlsoClashing
{
  public void IClashing.ClashingMethod() { }
  public void IAlsoClashing.ClashingMethod() { }
}

You need to explicitly cast to the specific interface type to use a clashing method.

(someClass as IClashing)?.ClashingMethod();

IClashing ic = ((IClashing)someClass);
if (ic) ic.ClashingMethod();

If you just define the unqualified clashing method, it will override all of them.

ICloneable

C#'s object class defines a protected MemberwiseClone() method that copies an object by copying the members.

To perform a deep copy you can utilize ICloneable.

public interface ICloneable
{
  object Clone(); // Just create a new object and copy the values yourself.
}

IComparable and IComparer

IComparable is notably utilized by Arrays.Sort.

public interface IComparable
{
  int CompareTo(object o); // -1 (lt), 0 (eq), 1 (gt).
}

IComparer is typically defined on a helper class, (e.g., ISBNComparer.Compare(Book a, Book b)). Arrays.Sort also can use this: Arrays.Sort(books, new ISBNComparer()).

public interface IComparer
{
  int Compare(object a, object b);
}
Clone this wiki locally