Let's say I have an interface as follows.
interface CardHolder : IEnumerable<Card>
{
/// <summary> ...
void PutCard(Card card);
/// <summary> ...
void PutCards(Card[] card);
/// Some more methods...
}
I implement it as follows.
public class ArrayCardHolder : CardHolder
{
private Card[] _cards;
private int _size = 0;
public ArrayCardHolder(int capacity)
{
_cards = new Card[capacity];
}
public void PutCard(Card card)
{
if (IsFull())
throw new Exception("This CardHolder is full. Capacity: " + Capacity());
_cards[_size++] = card;
}
public void PutCards(Card[] cards)
{
if (_size + cards.Length > _cards.Length)
throw new Exception("Adding the Cards would exceed this CardHolder its capacity. Capacity: " + Capacity());
for (int index = 0; index < cards.Length; index++)
_cards[_size++] = cards[index];
}
public IEnumerator<Card> GetEnumerator()
{
for (int index = 0; index < _size; index++)
yield return _cards[index];
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
///More methods.
}
Why can I not use the override
keyword in my ArrayCardHolder
(e.g. public void override PutCard(Card card) { ///implementation }
to indicate that the method implements (i.e. overrides) the interface? In that case, the project will refuse to build.
Why does it work however when overriding ToString()
? And why doesn't it work when implementing CompareTo(T t)
from IComparable<T>
?
What should I use instead? I'm worried that the documentation from the interface will not apply to my implementing methods. Such is the case in Java when the @Override
annotation is used.
Interface's methods are not overriden, they are implemented. You are confused with abstract/virtual methods which can be overriden.
Example:
public interface IFoo
{
void DoA();
}
public abstract class BaseFoo : IFoo
{
public void DoA() { } // *this HAS to be implemented*
public virtual void DoB() { }
}
public abstract class MyFoo : BaseFoo
{
// *this CAN be implemented, which would override the default implementation*
public override void DoB() { }
}
As others metioned, ToString
is a virtual
method of the base class object
, that is why you can override it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With