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

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

    Well, they aren't a bad idea I think. Dictionary<K, V> has a TryGetValue method which is a very good example why out parameters are sometimes a very nice thing to have.

    You should not overuse this feature of course, but it's not a bad idea per definition. Especially not in C# where you have to write down the out keyword in function declaration and call which makes it obvious what's going on.

    0 讨论(0)
  • 2020-12-25 11:17

    Some languages outside of .NET use them as do-nothing macros that simply give the programmer information about how the parameters are being used in the function.

    0 讨论(0)
  • 2020-12-25 11:18

    Out - Parameter are a bad idea in my opinion. They increase the risk of side effects and are hard to debug. The only good solution are function results and here is the problem: For function results, you have to create for every complex result a tuple or a new type. Now it should be fairly easy in c#, with anonymous types and generics.

    And by the way: I hate side effects too.

    0 讨论(0)
  • 2020-12-25 11:18

    I think the main reason is "...Although return values are commonplace and heavily used, the correct application of out and ref parameters requires intermediate design and coding skills. Library architects who design for a general audience should not expect users to master working with out or ref parameters."

    Please read more at: http://msdn.microsoft.com/en-us/library/ms182131.aspx

    0 讨论(0)
  • 2020-12-25 11:20

    They are a good idea. Because sometimes you just want to return multiple variables from one method, and you don't want to create a "heavy" class structure for this. The wrapping class structure can hide the way the information flows.

    I use this to:

    • Return key and IV data in one call
    • Split a person name, into different entities (first-, middle-, lastname)
    • Split the address
    0 讨论(0)
  • 2020-12-25 11:20

    I would have to agree with GateKiller. I can't imagine out parameters being too bad if Microsoft used them as part of the base library. But, as with all things, best in moderation.

    0 讨论(0)
提交回复
热议问题