Method "return" understanding

Hello,

Suppose we have the following two blocks of code.

Block 1 -->

// Method with return
static string CallMe(string name) {
	return name;
}

Block 2 -->

// Method without return
static string Yell(string item) {
	Console.WriteLine(item);
}

When I call them in the Main() method I get the following error -->

Main() -->

public static void Main (string[] args) {
		Console.WriteLine(CallMe("John"));
		Console.WriteLine(Yell("Orange"));
}

Error -->

main.cs(15,15): error CS0161: `MainClass.Yell(string)': not all code paths return a value
Compilation failed: 1 error(s), 0 warnings
compiler exit status 1

Questions -->

Why each method needs a return statement? How Console.WriteLine() differs from return? Why you can return only one value? Why I get the above error?

If you say it’s going to return something, it better

not each method needs a return statement, but looking at your Yell method:

static string Yell(string item) {
	Console.WriteLine(item);
}

you see string after static? This means your method returns a string, if you don’t want to return anything, use void instead.

writeLine writes output to the console, return hands data back to the caller.

you could return an array/list, which can contain multiple values. But that only one type can be returned is super useful once your code base grows, then people calling methods written by other developers team, know what to expect.

i think i covered this?

Nothing’s stopping you from storing multiple values in the value that you returned. See tuples, especially.

If you called the function and got its result, then where is the other result? …doesn’t really add up does it, similar to how if you promise to return a value, except you don’t, then what ends up being the result? Doesn’t add up.

What exactly means hands data back to the caller?

here:

CallMe("John")

you call the function, so return hands back the data to the function call, which you then decide to write to the console

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.