0

I am getting an error as nullreferenceexception while executing this code. Confused on what am I missing.

using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
using System.ComponentModel.DataAnnotations;
                    
public class Program
{
    public static void Main()
    {
        UserData user = new UserData{Id = 1, Username = "test", Password = "test"};
        RefreshToken data = new RefreshToken{Id=1, Token="dfaskjdkjsfa"};
        user.RefreshTokens.Add(data); *//getting error from this line*
        Console.WriteLine("Hello World");
    }
    
}

public class UserData
    {
        public int Id { get; set; }
        public string Username { get; set; }

        [JsonIgnore]
        public string Password { get; set; }

        [JsonIgnore]
        public List<RefreshToken> RefreshTokens { get; set; }
    }
public class RefreshToken
    {
        [Key]
        [JsonIgnore]
        public int Id { get; set; }
        
        public string Token { get; set; }
    }

And the error message is

System.NullReferenceException: Object reference not set to an instance of an object.

  • 2
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) - `user.RefreshTokens` is likely null. – Timothy G. May 13 '21 at 18:01
  • So I have to initialize Refreshtoken for user seperately like user.RefreshTokens = new List(); before adding values to it? – Sundar Acharya May 15 '21 at 02:48
  • Yes. You could modify the line `UserData user = new UserData{Id = 1, Username = "test", Password = "test"};` to `UserData user = new UserData { Id = 1, Username = "test", Password = "test", new List { new RefreshToken { Id=1, Token="dfaskjdkjsfa" } } };` and ditch the following two lines. – Timothy G. May 15 '21 at 03:22

0 Answers0