Method Parameter: VS Interface Generic Type

What are the arguments for using one or the other of these two implementations of the method (in the Example class)?

public interface IInterface { void DoIt(); } public class Example { public void MethodInterface(IInterface arg) { arg.DoIt(); } public void MethodGeneric<T>(T arg) where T: IInterface { arg.DoIt(); } } 

PS: If the method returns IInterface or T, I would choose the β€œgeneral” way to avoid further casting in type T, if necessary.

+6
source share
2 answers

Both seem the same, but not really.

The general version will not embed ValueType when transferring to where a β€œbox” is required as a non-standard version

Here is a small sample program and the corresponding IL that demonstrates the situation.

 void Main() { Example ex = new Example(); TestStruct tex = new TestStruct(); ex.MethodGeneric(tex); ex.MethodInterface(tex); } public interface IInterface { void DoIt(); } public class Example { public void MethodInterface(IInterface arg) { arg.DoIt(); } public void MethodGeneric<T>(T arg) where T : IInterface { arg.DoIt(); } } internal struct TestStruct : IInterface { public void DoIt() { } } 

Below is the corresponding portion of the generated IL

 IL_0001: newobj UserQuery+Example..ctor IL_0006: stloc.0 // ex IL_0007: ldloca.s 01 // tex IL_0009: initobj UserQuery.TestStruct IL_000F: ldloc.0 // ex IL_0010: ldloc.1 // tex IL_0011: callvirt UserQuery+Example.MethodGeneric IL_0016: nop IL_0017: ldloc.0 // ex IL_0018: ldloc.1 // tex IL_0019: box UserQuery.TestStruct //<--Box opcode IL_001E: callvirt UserQuery+Example.MethodInterface 

Although this is a matter of preference, although MethodGeneric is the one that will work better in the case of "ValueTypes"

+4
source

I suggest passing the interface as a simple parameter instead of using a general approach for the following reasons:

  • Simplified design, leading to better maintainability
  • More readable code, less professional knowledge.
  • Better Injection Dependency and IoC Support
  • Lack of reflection (I'm not sure about this, I am going to provide evidence because generics use reflection to understand the type)
+3
source

Source: https://habr.com/ru/post/957978/


All Articles