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!
I’m not sure how it is implemented in mono, but generic interfaces will help because the compiler creates a new function of the specific type for each different type used (internally, there are a few cases where it can utilize the same generated function). If a function of the specific type is generated, there is no need to box/unbox the type.
This is why the Collections.Generic library was a big hit at .NET 2.0 because collections no longer required boxing and became significantly more efficient.