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

后端 未结 5 811
心在旅途
心在旅途 2020-12-18 21:24

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.

publi         


        
5条回答
  •  抹茶落季
    2020-12-18 22:30

    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
    }
    

提交回复
热议问题