When to use C # out keyword by parameter

I have seen some developers use the out keyword in the parameter lists of void functions. I absolutely don’t understand what the pros and cons of the code below are:

 List<string> listOfResult; public void public void (out listOfResult) { //bla bla } 

vs

 public List<string> c(out listOfResult) { List<string> list= new List<string>(); //bla bla return list; } 

Are these two pieces of code excellent or are there any bindings to the out keyword?

+4
source share
4 answers

out keyword is convenient when you need to return more than one value from a function. A good example is the TryXXX methods, which return the status of an operation and not throw exceptions:

 public bool TryParse(string str, out int value); 

But I see no reason to use one out parameter with void methods ... Just return this value from your method. It will be much easier to use. For comparison:

 List<string> list; GetList(out list); // confusing method name 

FROM

 List<string> list = GetList(); // nice name, one line of code 

If getting a list can throw exceptions, you can create a method like this:

 List<string> list; if (TryGetList(out list)) // better than exception handling { // list was filled successfully } 
+3
source
Parameters

out is very convenient when you need to return more than one value from a function.

eg. Return is a list of results, but you can use the out parameter to return an error message when the returned list is null.

+1
source

Good syntax for returning multiple parameters. I personally think that it is almost always better to model the return of a method as a "new object / class".

It will be:

 class CResult { List<string> firstResult; List<string> secondResult; } public CResult c() { // do something return new CResult() {firstResult = ..., secondResult = ... }; } 

You can see more things related to this approach here .

+1
source

// from the keyword is used instead of the return function. we can use several parameters using the keyword public void outKeyword (from the string Firstname, out string SecondName) {Name = "Muhammad"; SecondName = "Ismail";

  } 

// when you click the Event button protected void btnOutKeyword_Click (object sender, EventArgs e) {line one, two; outKeyword (first, second); lblOutKeyword.Text = first + "" + second; }

0
source

All Articles