Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generics: If T is a return type, can it also be void? How can I combine these interfaces together?

I have the following interface that returns the generic parameter of type T using a callback...

public interface IDoWork<T>
{
    T DoWork();
}

however I also have the following interface as well, but it won't invoke a callback since it returns void.

public interface IDoWork
{
    void DoWork();
}

Can I combine these two interfaces and use runtime logic to determine the difference? How can I do that?

like image 618
makerofthings7 Avatar asked May 17 '12 22:05

makerofthings7


2 Answers

Unfortunately, they can't be combined.

You can see this in the framework - that's why there is a separate Task and Task<T> class, for example.

That being said, you can often share implementations in this type of scenario by using IDoWork<object> and passing null for values, etc.

like image 168
Reed Copsey Avatar answered Oct 10 '22 05:10

Reed Copsey


return type is a part of method signature, so T DoWork() and void DoWork() are different, and void is not a type and it is not a null. It is an indication there is nothing in evaluation stack on return from method.

like image 2
Val Bakhtin Avatar answered Oct 10 '22 04:10

Val Bakhtin