Add object to list of same object

I got this to classes:

public class NotifyUser : ContentPage
{
    public NotifyUser()
    {
        Friends = new List<FriendStatus>();
    }
    public string Namn { get; set; }
    public List<FriendStatus> Friends { get; set; }

}

public class FriendStatus
{
    public FriendStatus()
    {
        Name = "";
        Checked = false;
    }
    public string Name { get; set; }
    public bool Checked { get; set; }
}

And I got this method where I try to create a new object and add to the list.

public void AddFriend(string namn)
{
    namn = "Bob";
    string user = User.Identity.GetUserName();
    var loggedinuser = RavenSession
        .Load<ContentPage>("NotifyUser/" + user) as NotifyUser;

    var fr = new FriendStatus { Name = namn, Checked = false };

    loggedinuser.Friends.Add(fr);
    RavenSession.SaveChanges();
}

loggedinuser.Friends is a list of `frienstatus`, 

When I try to add my newly created object to the list I get an Additional information: Object reference not set to an instance of an object., can someone see what i have missed?

I thought my list was instantiated in the class with this line

public NotifyUser()
        {
            Friends = new List<FriendStatus>();
        }

Thanks!

Jon Skeet
people
quotationmark

I strongly suspect that this line is the problem:

var loggedinuser = RavenSession.Load<ContentPage>("NotifyUser/" + user) as NotifyUser;

loggedinuser will be null if the Load method actually returns something other than a NotifyUser. This is where it's better to use a cast than as - it means that if your type is wrong, you get a meaningful exception immediately rather than a NullReferenceException later on. (See my blog post on embracing exceptions for more about this.)

I don't know anything about RavenSession, but I wouldn't be surprised if you really wanted:

var loggedinuser = RavenSession.Load<NotifyUser>("NotifyUser/" + user);

If you must use RavenSession.Load<ContentPage>, you should change your code to use a cast instead of as. That way, if loggedinuser is null, that definitely means that Load returned null.

Additionally, you should use a debugger to check this sort of thing - that would easily have allowed you to differentiate between loggedinuser being null and loggedinuser.Friends being null.

people

See more on this question at Stackoverflow