what is use of out parameter in c#

后端 未结 9 1169
南方客
南方客 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:50

    Jon Skeet describes the different ways of passing parameters in great detail in this article. In short, an out parameter is a parameter that is passed uninitialized to a method. That method is then required to initialize the parameter before any possible return.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-07 16:53

    generally we cannot get the variables inside a function if we don't get by a return value. but use keyword "out" we can change it value by a function.

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