Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.Void in C#?

Tags:

c#

generics

I am currently working with .Net 2.0 and have an interface whose generic type is used to define a method's return type. Something like

interface IExecutor<T> {
  T Execute() { ... }
}

My problem is that some classes that implement this interface do not really need to return anything.

In Java you can use java.lang.Void for this purpose, but after quite a bit of searching I found no equivalent in C#. More generically, I also did not find a good way around this problem. I tried to find how people would do this with delegates, but found nothing either - which makes me believe that the problem is that I suck at searching :)

So what's the best way to solve this? How would you do it?

Thanks!

like image 995
anog Avatar asked Apr 10 '10 22:04

anog


1 Answers

You're going to have to either just use Object and return null, create your own object to represent void, or just make a separate interface that returns void.

Here's an idea for the second one:

public class Void
{
    public static readonly Void Instance = null; // You don't even need this line
    private Void() {}
}

that way someone can't create an instance of the class. But you have something to represent it. I think this might be the most elegant way of doing what you want.

Also, you might want to make the class sealed as well.

like image 101
Joel Avatar answered Sep 17 '22 20:09

Joel