-3

So on my quiz for my c# course one of the questions was

How would you declare a function that requires the calling code to modify the original contents of an input parameter?

And for some reason the answer is

void mystery(out double clue)

I thought to use the out parameter you must use the same data type as the variable? So like this

double mystery(out double clue)

Samurai
  • 189
  • 10
  • 5
    The return type of a method has nothing to do with an out parameter. Have you read something like https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier ? – Tieson T. Feb 15 '18 at 03:56
  • Related: https://stackoverflow.com/questions/19067611/out-parameter-in-c-sharp – TypeIA Feb 15 '18 at 03:57
  • 2
    You're conflating out _parameters_ and the _return value_ of the method. They are not the same thing. Look at `int.TryParse` - it returns a `bool`, and has an out parameter of `int`. – ProgrammingLlama Feb 15 '18 at 04:00
  • Somewhere along the line, you seem to have gotten confused by what was taught to you in your C# course. It is difficult to understand how you got to the point where you believe that the return type of a method has anything whatsoever to do with the types of the parameters, but that misunderstanding makes your question not useful and too broad. Either this is a "smack your forehead" goof, or you need detailed help from your course instructor. Either way, the question is not on-topic or appropriate for Stack Overflow. – Peter Duniho Feb 15 '18 at 04:19

1 Answers1

1

So, let consider the following pseudo-code:

R foo(T)

The function receives something of type T as input parameter. Also it returns something as a result of type R. In your quiz, the question was about T. So, the only way to let foo() to modify input parameter T is to add special signature around the T:

R foo1(out T t) {...}
R foo2(ref T t) {...}

Well, actually there are two ways to do that, you see? The difference is: foo1 can accept non-initialized values and then set them to proper value inside foo1() code. However, foo2 requires the parameter to be initialized before calling foo2(). Because null value can not be referenced, thus can not be modified.

And, as kindly emphasized by Hans Kesting in comments below, "out" means "requires the calling code to modify the original contents of an input parameter". So, this is it.

See these link for more details:

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42