Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

c# - 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 itWorkerd)
{
    itWorkerd = 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

    itWorkerd = // 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 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
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...