简体   繁体   中英

Why is return type void declared as struct in .NET?

AFAIK void means nothing in terms of programming language. So why in .Net framework it is declared as struct ?

using System.Runtime.InteropServices;

namespace System
{
  /// <summary>
  /// Specifies a return value type for a method that does not return a value.
  /// </summary>
  /// <filterpriority>2</filterpriority>
  [ComVisible(true)]
  [Serializable]
  [StructLayout(LayoutKind.Sequential, Size = 1)]
  public struct Void
  {
  }
}

System.Void is effectively a marker type - members like MethodInfo.ReturnType have to have some way of representing void , and System.Void is the way the .NET team chose to do so.

You shouldn't use it like a normal type. It's a workaround, effectively - a little like the F# Unit type , but not as fully integrated into the type system.

A method descriptor contains a field for the method's return type. While it would be possible to have that field be null for void functions, that would require that code which wants to eg report the method's return type say something like:

string theReturnType = theMethod.ReturnType ? theMethod.ReturnType.ToString() : "null";

rather than simply saying:

string theReturnType = theMethod.ReturnType.ToString();

There are enough cases where code has to do something with the method's return type that having to special-case null in all of them would be a far greater bother than simply having a dummy type "null" which can be returned.

Incidentally, although so far as I know void is the only type which is usable for a method return value but no other purpose, there are other cases where it would be useful to have a type which could be used for public return values, but not used in outside storage-location declarations, such as when writing a fluent interface (if outside code could be allowed to access members of biz.boz(3) , but could not store the value itself, then in a construct like biz.boz(3).foo(9).bar(2).build() , the foo method could know that it held the only reference anywhere in the universe to the object returned by boz(3) , and would thus be free to either mutate it or return a new instance, at its convenience).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM