Search code examples
c#language-design

Why use out keyword instead of assignment in c#?


I've been investigating the out keyword in C# after reading the section about it in C# in Depth. I cannot seem to find an example that shows why the keyword is required over just assigning the value of a return statement. For example:

public void Function1(int input, out int output)
{
    output = input * 5;
}

public int Function2(int input)
{
    return input * 5;
}

...
int i;
int j;

Function1(5, out i);
j = Function2(5);

Both i and j now have the same value. Is it just the convenience of being able to initialize without the = sign or is there some other value derived that I'm not seeing? I've seen some similar answers mentioning that it shifts responsibility for initialization to the callee here. But all that extra instead of just assigning a return value and not having a void method signature?


Solution

  • Usually out is used for a method that returns something else, but you still need to get a different value from the method.

    A good example is Int32.TryParse(input, out myVar) it will return true if it was successful and false otherwise. You can get the converted int via the out parameter.

    int myOutVar;
    
    if (Int32.TryParse("2", out myOutVar))
    {
       //do something with the int
    }else{
        //Parsing failed, show a message
    }