mmcglynn
mmcglynn

Reputation: 7662

Am I using Lists correctly?

In my page load, am I calling ReturnStuff() once or three times? If I am calling it three times, is there a more efficient 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;
}

Upvotes: 6

Views: 147

Answers (3)

squillman
squillman

Reputation: 13641

You're calling it 3 times. Call it once and save the results to a variable, then you can work with that variable.

Try this:

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

Upvotes: 1

user900360
user900360

Reputation:

3 times. following code will help you realize. go to Main function and call func() from there.

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 should call that function once, get the returned value in a local List<> variable and then access using the variable. like this:

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

Upvotes: 1

Joel Coehoorn
Joel Coehoorn

Reputation: 415840

You're calling 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 e-mail, I would write a function that returns an object composing a first name, last name, and e-mail:

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);
}

Upvotes: 13

Related Questions