开发者

How to add object to list (or other collection) that is inside another object?

I have this:

    public class Room
{
    public string RoomID { get; set; }
    public string RoomName { get; set; }
    public List<User> UsersInRoom { get; set; }

    //public IDuplexClient RoomCallbackChannel { get; set; }
}

As you can see there is an List that contains users in room.

But to actually make it work I need to add users, so I did this:

            User usr;
        Room roomi;
        if (userNameTest == null)
        {
            lock (_clients)
            {
                开发者_C百科usr = new User { UserID = sessionID, CallbackChannel = client, UserName = userName };
                roomi = new Room();
                roomi.RoomID = sessionID;
                roomi.RoomName = room;
                roomi.UsersInRoom.Add(usr);
                //roomi.UsersInRoom.Add(usr);
                _rooms.Add(roomi);
                //_clients.Add(usr);
            }
        }

and at line:

roomi.UsersInRoom.Add(usr);

I get NullReferenceException. What's going on ?


You haven't created a list - so roomi.UsersInRoom is null.

You could fix this by changing the line to:

roomi.UsersInRoom = new List<User>();
roomi.UsersInRoom.Add(usr);

Note that if you're using C# 3 or higher, you can use object and collection initializers to make all of this code simpler. Additionally, you could potentially make UsersInRoom a read-only property, setting the value to a new list within a Room constructor (or a variable initializer).

Unfortunately I don't have time to show all of this right now, but something like this for the object/collection initializers:

_rooms.Add(new Room {
    RoomId = sessionId,
    RoomName = room,
    UsersInRoom = new List<User> { 
        new User { 
            UserID = sessionID,
            CallbackChannel = client,
            UserName = userName
        }
    }
});

If you change it so that UsersInRoom is initialized by Room itself, this changes to:

_rooms.Add(new Room {
    RoomId = sessionId,
    RoomName = room,
    UsersInRoom = { 
        new User { 
            UserID = sessionID,
            CallbackChannel = client,
            UserName = userName
        }
    }
});


List<T>, is a reference type. The default value for a reference type is null.

You need to initialise the List before you start adding items to it.

roomi.UsersInRoom=new List<User>();


Have you made sure the List is initialized? List is an object so you have to 'create' it, like so:

List<User> nameOfList = new List<User>();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜