I have a C# interface with certain method parameters declared as object
types. However, the actual type passed around can differ depending on the class implementing the interface:
public interface IMyInterface
{
void MyMethod(object arg);
}
public class MyClass1 : IMyInterface
{
public void MyMethod(object arg)
{
MyObject obj = (MyObject) arg;
// do something with obj...
}
}
public class MyClass2 : IMyInterface
{
public void MyMethod(object arg)
{
byte[] obj = (byte[]) arg;
// do something with obj...
}
}
The problem with MyClass2 is that the conversion of byte[]
to and from object
is boxing and unboxing, which are computationally expensive operations affecting performance.
Would solving this problem with a generic interface avoid boxing/unboxing?
public interface IMyInterface<T>
{
void MyMethod(T arg);
}
public class MyClass1 : IMyInterface<MyObject>
{
public void MyMethod(MyObject arg)
{
// typecast no longer necessary
//MyObject obj = (MyObject) arg;
// do something with arg...
}
}
public class MyClass2 : IMyInterface<byte[]>
{
public void MyMethod(byte[] arg)
{
// typecast no longer necessary
//byte[] obj = (byte[]) arg;
// do something with arg...
}
}
How is this implemented in .NET vs Mono? Will there be any performance implications on either platform?
Thank you!
It's often useful to define interfaces either for generic collection classes, or for the generic classes that represent items in the collection. To avoid boxing and unboxing operations on value types, it's better to use generic interfaces, such as IComparable<T>, on generic classes.
You can declare generic type parameters in interfaces as covariant or contravariant. Covariance allows interface methods to have more derived return types than that defined by the generic type parameters.
Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.
You will get the same benefits in Mono that you do in .NET.
We strongly recommend that you use Mono 1.9 or Mono 2.0 RCx in general, as generics support only matured with 1.9.
The problem with MyClass2 is that the conversion of byte[] to and from object is boxing and unboxing, which are computationally expensive operations affecting performance.
There is no boxing involved with array types, even one with value type elements. An array is a reference type.
The overhead on (byte[]) arg is minimal at best.
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