+ 3
My understanding is that void is used before a method that will not return a result. But it's also used in front of methods that are doing a calculation, and definitely returning a result. Where am i misunderstanding this?
Void keyword
4 odpowiedzi
+ 1
Thank you guys for trying to help me, and being patient. I'm still not getting where my misunderstanding is. This is an example of code, from the course, that is confusing me. I'm looking at two things here - 1) the method's type is void. 2) it returns a value
..............................................
static void Sqr (ref int x)
{
x=x*x;
}
static void Main ();
{
Int a = 3;
Sqr (ref a);
Console.WriteLine(a);
//outputs 9
}
..........................................
We keep saying that void is for not returning a value - which i can understand for performing functions like causing a string to be printed to the screen - but this code has void, and is clearly doing a calculation, and returning a value. So what is my misunderstanding of void not returning a value?
0
void means method does not return result, but it does not mean it does nothing. It may return data in parameters marked as 'out', store data in his objects fields, modify properties or call methods upon other objects passed to it as parameters. Loads of things might be done in a method, while it does not always need or can return result.
If you mean you've seen "return X;" in a void method, then it should not compile. But you can use "return;" statement to short circuit your method, very useful in some cases.
0
From "C# In a Nutshell" book:
"A method performs an action in a series of statements. A method can receive input data from the caller by specifying parameters and output data back to the caller by specifying a return type. A method can specify a void return type, indicating that it doesn't return any value to its caller. A method can also output data back to the caller via ref/out parameters."
In your example the variable 'a' is passed by reference (ref a, ref int x), you can read more here https://msdn.microsoft.com/en-us/library/14akc2c7.aspx . If passing by reference or as out parameter, the changes to variable in method are reflected in the caller.
In this case changes to x (line "x = x * x;") are reflected in variable a.
As an experiment - remove ref keywords and see that it now prints 3.
TL-DR: Technically your method does return a value, just stores it in a variable passed by reference.
- 1
void = returns nothing
any other datatype like int = returns a thing