You cannot implement interface methods without having a derived class. However, you can add derived information to an interface by means of extension methods, if your interface provides enough basic functionality.
For an array, you could have the interface method IndexCheck
and derive the array length by checking for the last valid index.
public interface IArrayOperation
{
bool IndexCheck(int index);
}
public static class TestArray
{
public static int GetArrayLength(this IArrayOperation arrayOperation)
{
int len = 0;
while (arrayOperation.IndexCheck(len)) { ++len; }
return len;
}
}
Or you could have an array length and derive the index check
public interface IArrayOperation
{
int GetArrayLength();
}
public static class TestArray
{
public static bool IndexCheck(this IArrayOperation arrayOperation, int index)
{
return index >= 0 && index < arrayOperation.GetArrayLength();
}
}
In both cases, you can later use an IArrayOperation
variable with both methods
IArrayOperation instance = /* some concrete derived class */;
bool checkResult = instance.IndexCheck(0);
int lengthResult = instance.GetArrayLength();
Your derived class instances need to implement the methods that are actually part of the interface, but the extension methods are available without implementation per instance.