0

i need to build a list in a function, then return it to a another list variable the problem is: inside the function the list is built properly but when i return it to the outer variable it seems like all the elements of the outer list are all similar to the last one added to it inside the function. what is the reason of this?

this is my code:

List<stu> fillObject(SqlDataReader rd)
    {
        List<stu> stList = new List<stu>();
        stu stObj = new stu();
        while (rd.Read())
        {
            stObj.username = rd["username"].ToString();
            stObj.password = rd["password"].ToString();
            stObj.fname = rd["fname"].ToString();
            stObj.lname = rd["lname"].ToString();
            stObj.faculty = rd["faculty"].ToString();
            stList.Add(stObj);

        }
        return stList;
    }

here is the call of the function:

var friendsList = fillObject(rd);

so looping though 'friendList' would give the same last object added in the builder function.

3 Answers 3

1

Try this

List<stu> fillObject(SqlDataReader rd)
    {
        List<stu> stList = new List<stu>();

        while (rd.Read())
        {
            stu stObj = new stu();
            stObj.username = rd["username"].ToString();
            stObj.password = rd["password"].ToString();
            stObj.fname = rd["fname"].ToString();
            stObj.lname = rd["lname"].ToString();
            stObj.faculty = rd["faculty"].ToString();
            stList.Add(stObj);

        }
        return stList;
    }

what you were missing is initializing stu inside while, due to which there was only one stu object that is being added again and again into stList.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to create New STU object inside the loop, Otherwise you keep changing the same referenced object.

1 Comment

i need x-y, but i don't know who is bigger is there a max(x,y)-min(x,y) in C#?
0

Try This :

List<stu> fillObject(SqlDataReader rd)
{
    List<stu> stList = new List<stu>();
    //stu stObj = new stu();
    while (rd.Read())
    {

       stList.Add(new stu 
       {
        username = rd["username"].ToString(),
        password = rd["password"].ToString(),
        fname = rd["fname"].ToString(),
        lname = rd["lname"].ToString(),
        faculty = rd["faculty"].ToString()

      });

    }
    return stList;
}

2 Comments

do you really mean: stObj.Add() ?
there is no need to create stu class object inside loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.