what is use of out parameter in c#

后端 未结 9 1166
南方客
南方客 2021-02-07 16:27

Can you please tell me what is the exact use of out parameter?

Related Question:
What is the differen

9条回答
  •  深忆病人
    2021-02-07 16:52

    The typical use case is a method that needs to return more than one thing, so it can't just use the return value. Commonly, the return value is used for a success flag while the out parameter(s) sets values when the method is successful.

    The classic example is:

    public bool TryGet( 
       string key,
       out string value
    )
    

    If it returns true, then value is set. Otherwise, it's not. This lets you write code such as:

    string value;
    if (!lookupDictionary.TryGet("some key", out value))
      value = "default";
    

    Note that this doesn't require you to call Contains before using an indexer, which makes it faster and cleaner. I should also add that, unlike the very similar ref modifier, the compiler won't complain if the out parameter was never initialized.

提交回复
热议问题