-1

I have the following code in c#

class Sample{
public void sum(out int num1,int num2)
{
}
public void print()
{ int i=12;
sum(out i,10);
Console.WriteLine(i);
}
}

I have read that it works like 'ref',then why the following code give error saying "the out parameter 'num1' must be assigned before control leaves the current method",even i am not writing any statement there or not using num1 and i already assign it the value in callee method?

if i am not using or initialise out parameter,then why it is not initialized to its default value,for here num1=0,and return that value to calee method?

dnyaneshwar
  • 1,296
  • 3
  • 18
  • 26

4 Answers4

3

This is by design.

From out parameter modifier (C# Reference)

Although variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
3

out is out. You can imagine that it's an alternative way to return the values. The significant difference between return and out is that you can only return one value, but out a various number of values. It's especially useful when your method needs to output more than just one value, such as bool Dictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value).

The error you see is like when you declare a method which returns a value without specifying what to return. The out arguments must be assigned before the code reaches a reachable endpoint. Write a statement which assigns a value to the out parameter is an usual way to get rid of the error:

public static void OutOfAssgnment<T>(out T value) {
    value=default(T);
}

But there are, in fact, at least three approaches other to make it compile:

public static void OutOfAnotherOut<T>(out T value) {
    OutOfAnotherOut(out value); // not necessarily be recursive, just an example
}

public static void OutOfThrowing<T>(out T value) {
    throw new Exception();
}

public static void OutOfInfiniteLoop<T>(out T value) {
    for(; ; )
        ;
}

The latter two don't assign the value of the out parameter, but make the endpoint unreachable would also compile.

Ken Kin
  • 4,503
  • 3
  • 38
  • 76
1

Similar to how a function with a return type must return a value on all code paths, a function with an out parameter must also assign a value to the out parameter on all code paths.

Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80
1

That's the definition of the out parameter. It means it doesn't have to, and usually won't, be set before being called, and the method with the out parameter will set it. If you want to set it before hand, and be able to modify it in the method, you should use ref instead of out.

Nikhil
  • 1,121
  • 2
  • 11
  • 27