What does a void subroutine return?

后端 未结 2 1607
清酒与你
清酒与你 2021-01-28 07:46

I was just doing an assessment on pluralsight and was given the following question.

\"What does a void subroutine return?\"

I was under the impression that a vo

2条回答
  •  萌比男神i
    2021-01-28 08:03

    System.Void is not nothing , it's a struct hence a value type.

    However, a method that is a Sub(VB.NET) or "returns" void(C#) does not really return a value. So you cannot write something like this:

    System.Void nothing = Foo(); // Foo is a void-method 
    

    This doesn't compile ("System.Void cannot be used from C# -- use typeof(void) to get the void type object"). Related: Why not System.Void?


    As Jeroen and others have mentioned, actually a void method does really not return anything, so the correct answer was: "It returns nothing".

    MSDN mentioned that it's only useful in reflection:

    "The Void structure is used in the System.Reflection namespace, but is rarely useful in a typical application. The Void structure has no members other than the ones all types inherit from the Object class."

    If you look at the tooltip on the void-keyword you see that it maps to System.Void. But again, that doesn't mean that it is returned from the method. It's just a placeholder for a non-existing return value. I guess that void also exists due to historical reasons since C# is based on C.

    Also worth reading: Why does void in C mean not void?

提交回复
热议问题