Am I using lists correctly?

In my page load, do I call ReturnStuff() one or three times? If I call it three times, is there a better way to do this?

 protected void Page_Load(object sender, EventArgs e) { string thing1 = ReturnStuff(username,password)[0]; string thing2 = ReturnStuff(username, password)[1]; string thing3 = ReturnStuff(username, password)[2]; } public static List<string> ReturnStuff(string foo, string bar) { // Create a list to contain the attributes List<string> Stuff = new List<string>(); // Some process that determines strings values based on supplied parameters Stuff.Add(fn); Stuff.Add(ln); Stuff.Add(em); return Stuff; } 
+6
source share
3 answers

You call it three times. Here is a more efficient way:

 protected void Page_Load(object sender, EventArgs e) { var stuff = ReturnStuff(username,password); string thing1 = stuff[0]; string thing2 = stuff[1]; string thing3 = stuff[2]; } 

But more than that, if you have a first name, last name, and email address, I would write a function that returns the object that makes up the first name, last name, and email address:

 public class User { public string LastName {get;set;} public string FirstName {get;set;} public string EMail {get;set;} } public static User GetUser(string username, string password) { // Some process that determines strings values based on supplied parameters return new User() {FirstName=fn, LastName=ln, EMail=em}; } protected void Page_Load(object sender, EventArgs e) { var user = GetUser(username,password); } 
+13
source

You name it 3 times. Call it once and save the results in a variable, then you can work with this variable.

Try the following:

 var stuff = ReturnStuff(username,password); string thing1 = stuff[0]; string thing2 = stuff[1]; string thing3 = stuff[2]; 
+1
source

3 times. The following code will help you understand. go to the main function and call the func () function.

 class howmanytimescallingafunction { public static int i = 0; public List<string> fun() { List<string> list = new List<string> { "A", "B", "C" }; i++; return list; } public void func() { Console.WriteLine(fun()[0]); Console.WriteLine(i); Console.WriteLine(fun()[1]); Console.WriteLine(i); Console.WriteLine(fun()[2]); Console.WriteLine(i); } } 

You must call this function once, get the return value in the local variable List <> and then access it with the variable. eg:

 List<string> list = function-that-returns-List<string>(); list[0]; //Do whatever with list now. 
+1
source

Source: https://habr.com/ru/post/911227/


All Articles