Forbidden Void type in C#

I’ve had this come up a couple of times.  I’d really like to be able to do something like this:

Func<bool, Void> whyNot = test => Console.WriteLine(test);

This is equivalent to:

Action<bool> okThisWorks = test => Console.WriteLine(test);

Although an actual Void type exists in the .NET Framework.  There error is very specific:

error CS0673: System.Void cannot be used from C# -- use typeof(void) to get the void type object

It even calls out the C# language!  Having a first class, supported Void type helps out quite a bit in various Functional Programming scenarios I’ve run into, and I’ve always had to resort to using the Action delegates.

I’m sure there’s a good reason for the explicit forbidding here, much like the generic variance issues.  Not being on the C# team, I can’t really think of any.  Anyone else have any insight here?

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in C#. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://jagregory.com James Gregory

    “Void Structure
    Specifies a return value type for a method that does not return a value.”

    Nice oxymoron.

  • http://www.peterRitchie.com/blog Peter Ritchie

    MSIL doesn’t support instantiation of Func(bool,void); so I assume it doesn’t support void as a type-parameter at all.

  • http://www.peterRitchie.com/blog Peter Ritchie

    Section 9.4 of ECMA 335, Partition II:
    “The following kinds of type cannot be used as arguments in instantiations (of generic types or methods):

    • void (e.g., List is invalid)

  • http://rockingtech.blogspot.com Robert Markovo

    do not try any dlls from the C# library and make it solely from F#, it is much efficient, faster and you will find it all. I will get back in touch with exact info soon , till then surf the MSDN.

  • pip010

    void should bare simply the meaning of NOTYPE, as null for no value

    so when i do in generics

    class MyClass : MyBaseClass

    {}

    then i can check for typeof(T2) is void ?