mackwerk
mackwerk

Reputation: 1687

Adding an item to list string[]

I am trying to add a few rows I got from a DataTable to my list using this struct:

protected struct roleProperties
{
    public string roleName { get; set; }
    public string[] functionTitle { get; set; }
}

As you can see I want more strings inside the method Title string

I have been trying to do it like this:

public void getRoleFuncs(int roleId)
{
    List<roleProperties> roles = new List<roleProperties>();
    int i = 1;

    SqlParameter ro_id = new SqlParameter("@ro_id", roleId);
    string q = "SELECT ro_name, fu_title FROM roles INNER JOIN rolefunctions ON roles.ro_id = rolefunctions.fk_role_id INNER JOIN functions ON rolefunctions.fk_func_id = functions.fu_id WHERE ro_id = @ro_id";
    SqlDataReader r = gm.returnReader(q, ro_id);
    while (r.Read())
    {
        roleProperties item = new roleProperties();
        item.roleName = r["ro_name"].ToString();
        foreach (IDataRecord str in r)
        {
            item.functionTitle[i] = r["fu_title"].ToString();
            i++;
        }
        roles.Add(item);
    }
}

But I get a null reference on this line:

item.functionTitle[i] = r["fu_title"].ToString();

Can anyone see what I am doing wrong?

Upvotes: 1

Views: 13809

Answers (3)

scartag
scartag

Reputation: 17680

Initialize the array first.

item.functionTitle = new string[n]; // where n is an int

Upvotes: 1

Rune FS
Rune FS

Reputation: 21742

Your array is not initialized and hence null since you do not know the size of the array you are going to need it seems a more suitable approach to use a list instead

change your struct to

protected class roleProperties
{
    public string roleName { get; set; }
    public IList<string> functionTitle { get; private set;}
    public roleProperties(){
        functionTitle = new List<string>();
    }
}

and then change

item.functionTitle[i] = r["fu_title"].ToString();

to

item.functionTitle.Add(r["fu_title"].ToString());

I've changed the struct to a class because it's mutable and mutable structs are evil.

Upvotes: 1

Jon
Jon

Reputation: 437454

item.functionTitle is null because arrays are reference types and you have not initialized the property anywhere (so it has the default value: null for a reference type).

Even if that was not a problem (let's say functionTitle is an empty array) item.functionTitle[i] would again throw because it tries to access an index that is out of bounds. And finally, you have an off-by-one error: the first element in an array has the index 0, not 1.

You can fix all of the above by changing the code to

while (r.Read())
{
    roleProperties item = new roleProperties();
    item.roleName = r["ro_name"].ToString();
    item.functionTitle = r.Select(o => o["fu_title"].ToString()).ToArray();
    roles.Add(item);
}

Upvotes: 3

Related Questions