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

后端 未结 5 810
心在旅途
心在旅途 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:20

    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.

提交回复
热议问题