DaveDev
DaveDev

Reputation: 42215

Why can't an out parameter have a default value?

Currently when trying to do something in a method that takes an out parameter, I need to assign the value of the out parameter in the method body, e.g.

public static void TryDoSomething(int value, out bool itWorked)
{
    itWorked = true;

    if (someFavourableCondition)
    {
        // if I didn't assign itWorked variable before this point, 
        // I get an error: "Parameter itWorked must be assigned upon exit."
        return;
    }

    // try to do thing

    itWorked = // success of attempt to do thing
}

I'd like to be able to set a default value of the itWorked parameter so I don't have to arbitrarily set the value in the body of the method.

public static void TryDoSomething(int value, out bool itWorked = true)
{
    if (someFavourableCondition)
    {
        // itWorked was already assigned with a default value
        // so no compile errors.
        return;
    }

    // try to do thing

    itWorked = // success of attempt to do thing
}

Why is it not possible to assign a default value for an out parameter?

Upvotes: 24

Views: 28837

Answers (7)

Enrico Savazzi
Enrico Savazzi

Reputation: 1

A method parameter declared with 'out' cannot have its value assigned by the caller. So a default value cannot be assigned during the call, either.

Also, you must always initialize an 'out' parameter in the method's body before using the parameter or returning from the method. This would overwrite any default value.

This is the whole point with the 'out' modifier. If you want a different behavior, check out the 'ref' and 'in' modifiers.

Upvotes: 0

Andrés Fg
Andrés Fg

Reputation: 136

If you have two calls to a method that uses 'out' or 'ref', and you want to avoid to split the method up in two, if one of the calls is not using these parameters, an elegant solution to avoid the warning from the compiler that "the value is not being used" (or something similar), is to use something like this:

method("hi", out _);

Upvotes: 0

Ben Wesson
Ben Wesson

Reputation: 639

I appreciate this isn't exactly answering the original question, but I'm unable to contribute to the comments. I had the same question myself so found myself here.

Since C#7 now allows out parameters to effectively be variable declarations in the calling scope, assigning a default value would be useful.

Consider the following simple method:

private void ResolveStatusName(string statusName, out string statusCode)
    {
        statusCode = "";
        if (statusName != "Any")
        {
            statusCode = statusName.Length > 1
                ? statusName.Substring(0, 1)
                : statusName;
        }
    }

It felt intuitive to modify it like so:

 private void ResolveStatusName(string statusName, out string statusCode = "")
    {
        if (statusName != "Any")
        {
            statusCode = statusName.Length > 1
                ? statusName.Substring(0, 1)
                : statusName;
        }
    }

The intention was to not only declare the statusCode value, but also define it's default value, but the compiler does not allow it.

Upvotes: 5

Muhammad Zaighum
Muhammad Zaighum

Reputation: 560

The out method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method. Declaring an out method is useful when you want a method to return multiple values. A method that uses an out parameter can still return a value. A method can have more than one out parameter. To use an out parameter, the argument must explicitly be passed to the method as an out argument. The value of an out argument will not be passed to the out parameter. A variable passed as an out argument need not be initialized. However, the out parameter must be assigned a value before the method returns.

Compiler will not allow you to use out parameter as default parameter because it is violating its use case. if you don't pass it to function you cannot use its value at calling function.

if you could call below function like TryDoSomething(123) then there is no use of out parameter because you will not be able to use value of itWorked

public static void TryDoSomething(int value, out bool itWorkerd = true)
{
    if (someFavourableCondition)
    {
        // itWorked was already assigned with a default value
        // so no compile errors.
        return;
    }

    // try to do thing

    itWorkerd = // success of attempt to do thing
}

Upvotes: 0

David Crowell
David Crowell

Reputation: 3813

Default parameter values are the default value for parameters passed in to the method. You have to specify a variable to pass for an out parameter so that you can get the returned value.

Your first example, in a way, has a default, set at the beginning of the method.

Upvotes: 0

serdar
serdar

Reputation: 1628

Even if it allowed you to give a default value like that, it would still require you to assign value for the parameter for all returns. So your default value will be overridden.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613432

Default values are available for parameters passed by value. The parameter is still passed to the function but if the code omits the parameter, the compiler supplies the missing value.

Your proposed feature is quite different. Instead of the caller omitting to pass the value, you propose to allow the implementer of the function to omit setting the value. So, this is a quite different feature. Why was it not implemented? Here are some possible reasons:

  1. Nobody thought to implement this feature.
  2. The designers considered the feature and rejected it as not useful enough to be worth the cost of implementing.
  3. The designers considered the feature and rejected it as being confusing because it uses similar syntax to default value parameters, but has a quite different meaning.

Upvotes: 12

Related Questions