Real-world examples where C# 'out' parameters are useful?

后端 未结 8 876
逝去的感伤
逝去的感伤 2020-12-29 06:46

I\'m reading up on core C# programming constructs and having a hard time wrapping my head around the out parameter modifier. I know what it does by reading but

8条回答
  •  孤独总比滥情好
    2020-12-29 07:20

    there are many scenarios where you would use it, but the main one would be where your method needs to return more then one parameter. Take, for example, the TryParse methods on int type. In this case, instead of throwing an exception a bool is returned as a success/failure flag and the parsed int is return as the out param. if you were to call int.Parse(...) you could potentially throw an exception.

    string str = "123456";
    int val;
    if ( !int.TryParse(str,out val) )
    {
    // do some error handling, notify user, etc.
    }
    

提交回复
热议问题