What exactly is Void keyword in C#?

Many developers are thinking, that it is possible in C# to declare a method which will return nothing. That’s a half of true, because the Void keyword has the structure behind of that!

Let’s take a look, on what Reflector is showing us:

[Serializable, StructLayout(LayoutKind.Sequential, Size=1), ComVisible(true)]
public struct Void
{
}

Even more, we could look on IL version of that:

.class public sequential ansi serializable sealed beforefieldinit Void
 extends System.ValueType
{
.custom instance void System.Runtime.InteropServices.ComVisibleAttribute::.ctor(bool) = { bool(true) }
}

What’s that mean? A couple of things:

  • Void is the sealed class derived from System.ValueType in terms of CLR and it is just the structure in C#, but …
  • … when you defining structure in C# you cannot write constructor without parameters because it is declared by default. So in every typical structure defined in C# you will find something like that in IL:
.method private hidebysig specialname rtspecialname static void .cctor() cil managed
    {
    }

There is nothing like that so you cannot invoke new Void() in your code! Then compiler is treating in special way this structure (keyword) and we have the simulation of returning nothing.

Just as simple as that 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s