Annoying Void in C# / Java / alike

One thing which regularly annoys me in C# and Java is the void type. Basically the void type is not a subtype of object, which makes it giant. Now when you write something which accepts a function as an argument you need two version: A version which accepts a function which returns something and a version which accepts a ‘void-returning’-function (the Action delegates in C#).

Void Is Not Cool Enough

Void Is Not Cool Enough

In my code I often end up doing something like this:

class Example
{
// Stuff like transactions, run in contexts, binding methods etc etc.
public T WithSomeContext<T>(Func<T> runInContext)
{
// do magic and stuff
var result = runInContext();
// do other stuff
return result;
}
// Doublicate to also accept Void returns
public void WithSomeContext(Action runInContext)
{
WithSomeContext<object>(() =>
{
runInContext();
return null;
});
}
public void UseIt()
{
var valueOne = 1;
var valueTwo = 2;
// with return value
var sum = WithSomeContext(() => valueOne + valueTwo);
WithSomeContext(() => Console.WriteLine("Hi-There"));
}
}

That’s just boilerplate which I really don’t need. In many other languages, for example Scala, this is handled more elegantly. The void-type (often called Unit) is a regular type. And void/unit values just represent ‘void/unit‘:

class Example{
def withContext[T](runInContext:()=>T):T ={
// do magic and stuff
val result = runInContext();
// do other stuff
return result;
}
// no need for another method.
// Our withContext also can accept 'void'-returns aka Unit
def useIt() {
val valueOne = 1;
val valueTwo = 2;
var sum = withContext(() => valueOne + valueTwo);
withContext(() => println("Hi-There"));
}
}

Yes, I know, it’s not the end of the (programming) world. There are tons of other issues which lead to more boiler-plate. Anyhow, it is such a little thing and still so god damn annoying. God help us that no new programming includes the same little weakness =).

Tagged on: , ,