0

I want to make the return type of my method generic. The caller will decide which type it should expect.

Actually my method will be a member of interface and the class which will implement it will have a decision making block to delegate the work to other methods.

Hence I want to make the return type of the interface method as generic.

I can achieve this by using dynamic or object keyword or c# generic type.

I am not able to figure it out which will be the best option to achieve it and what are the limitations and advantages of each type.

 public interface ICoreWrapper
 {
    Response<T> ExecuteDeviceCommand<T>(DeviceCommand deviceCommand, object param = null);

 }

Please suggest me.

Thanks in advance.

1 Answers1

0

If you do not know the type at compile time you could use dynamics but they will be slower because they are using runtime invocation and less safe because if the type doesn't implement the method you are attempting to invoke you will get a runtime error.

Use dynamic return type, Based on the input type return the appropriate object.

Nambirajan S
  • 201
  • 1
  • 6
  • @Nambiranjan S I solved the problem using generics, but I want to know is it a good approach or going with dynamic is better. If so, what is the cause behind this ? – S Anil Kumar Dora Nov 26 '15 at 09:09
  • If you known the type at compile time, always go with generics and its a good approach. [see here](http://stackoverflow.com/questions/828303/does-the-c-sharp-4-0-dynamic-keyword-make-generics-redundant) – Nambirajan S Nov 26 '15 at 09:19