Why can't C# use System.Void type?

G

Guest

With generics in .NET 2, there are certain scenarios in which using
System.Void would be useful:

TReturnType MyFunction<TReturnType>()
{
return default(TReturnType);
}

Above is a simple function that would allow me to make a generic method that
would return any type I instanciate the method with. But what if I wanted to
return void? Well, I will just call MyFunction<System.Void>(). Unfortunately,
the compiler issues an error saying System.Void isn't accessible in C#.

What is the reasoning behind this? Why are we not allowed to use System.Void
in C#?
 
D

Daniel O'Connell [C# MVP]

Judah said:
With generics in .NET 2, there are certain scenarios in which using
System.Void would be useful:

TReturnType MyFunction<TReturnType>()
{
return default(TReturnType);
}

Above is a simple function that would allow me to make a generic method
that
would return any type I instanciate the method with. But what if I wanted
to
return void? Well, I will just call MyFunction<System.Void>().
Unfortunately,
the compiler issues an error saying System.Void isn't accessible in C#.

What is the reasoning behind this? Why are we not allowed to use
System.Void
in C#?

Basically is that you can't actually return a void, have a parameter, field,
or variable of type void, or use a method that has a void return type
generically(how do you use a method that returns a value only sometimes?
Methods that return void push nothing on the stack, methods that return
something push something on the stack, the implementation of the two are
very different.) The sole legal use of void would be to specify that a
method does not return a value, and thus having a method that is returns
values only sometimes is quite different than a method that is guarenteed to
return a value or guarenteed not to.

Consider this code, which is functionally equivilent to yoru original code.
Does it actually make any sense when looked at like this?:

TReturnType MyFunction<TReturnType>()
{
TReturnType type = default(TReturnType);
return type;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top