Alex Rivera | Logout

what is use of out parameter in c#

Asked 2009-07-22T13:01:32.307
13

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

Related Question:
What is the difference between ref and out? (C#)

Edit
Report

1 Answer

1

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.

answered 2009-07-22T13:04:54.833

Your Answer