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

后端 未结 22 2896
余生分开走
余生分开走 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:31

    It's not always a bad idea to use out parameters. Usually for the code that tries to create an object based on some form of input it's a good idea to provide a Try method with out parameters and boolean return value, not to force the method consumer to wrap try catch blocks all over, not to mention the better performance. Example:

    bool TryGetSomeValue(out SomeValue value, [...]);
    

    this is a case where out parameters are a good ideea.

    Another case is where you want to avoid costly large structure passing between methods. For example:

    void CreateNullProjectionMatrix(out Matrix matrix);
    

    this version avoids costly struct copying.

    But, unless out is needed for a specific reason, it should be avoided.

提交回复
热议问题