Why are 'out' parameters in .NET a bad idea?

后端 未结 22 2846
余生分开走
余生分开走 2020-12-25 10:54

Why are \'out\' parameters in .NET a bad idea?

I was recently asked this, but I had no real answer besides it\'s simply unnecessarily complicating an application. Wh

22条回答
  •  情歌与酒
    2020-12-25 11:22

    The wording of the question is of the "Have you stopped hitting your wife?" variety—it assumes that out parameters are necessarily a bad idea. There are cases where out parameters can be abused, but…

    • They actually fit very well in the C# language. They are like ref parameters except that the method is guaranteed to assign a value to it and the caller doesn't need to initialize the variable.

    • Normal return values for functions are pushed onto the stack where they are called and exited. When you supply an out parameter, you're giving the method a specific memory address to stick the result in. This also allows for multiple return values, though using a struct often makes more sense.

    • They are wonderful for the TryParse Pattern and also provide metadata for other things like in the case of SQL-CLR where out parameters are mapped to out parameters of a stored procedure signature.

提交回复
热议问题