开发者

List<string> won't add XML-generated values when their valid

开发者 https://www.devze.com 2023-01-26 17:23 出处:网络
My 开发者_开发百科program errors out with a Null Reference Exception when it attempts to add to a List

My 开发者_开发百科program errors out with a Null Reference Exception when it attempts to add to a List

Code for the for loop

for (int i = 0; i < UserCourses.Length; i++)
                        {
                            CurrentUser.Course_ID.Add(UserCourses[i]);
                        }

Code for CurrentUser (which is a new of type User)

public class User
        {
            public int coursenum;
            public string Username;
            public string Password;
            public string FirstName;
            public string LastName;
            public string Email_Address;
            public string User_Type;
            public List<string> Course_ID;
            public List<Course> Course;
        }

I had it display the UserCourses[i] and it displayed successfully with the correct information, what am I doing wrong here?


You are not initializing the Course_ID property to contain a reference to a new List<string>. So you are calling Add on a null reference.

(Also, you might consider using the AddRange method, which will add the whole array/list you are attempting to add with one line of code. This will eliminate the need to write your own loop.)

0

精彩评论

暂无评论...
验证码 换一张
取 消