C
C#2y ago
surwren

System.NullReference Exception Adding to a Dictionary [Answered]

I'm really confused why this is happening. The dictionary in question is an attribute of a class that I've created. Lecturer class:
public class Lecturer
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username { get; set; }

public Dictionary<string, string> CourseLecturers { get; set; }


}
public class Lecturer
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username { get; set; }

public Dictionary<string, string> CourseLecturers { get; set; }


}
I definitely do instantiate a new Lecturer object:
Lecturer lecturer = new Lecturer();
Lecturer lecturer = new Lecturer();
However, it refuses to assign the values taken from the SQL reader into the lecturer's dictionary attribute (CourseLecturers) In the images attached, you can see that the reader successfully assigns the relevant values from the DB table into the variables, but the variables cannot be assigned to the dictionary for some reason. This is driving me insane, I've been debugging for 6 hours
8 Replies
surwren
surwren2y ago
I suspect it's because it's trying to {get} from empty dictionary before it invokes {set}, but I don't know how to get around this
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
surwren
surwren2y ago
Oh i fixed it by declaring
CourseLecturers=new Dictionary...
CourseLecturers=new Dictionary...
in the constructor but your syntax looks way neater, i will try it
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
surwren
surwren2y ago
Huh Idgi
Tvde1
Tvde12y ago
you can use = new() instead of = new Dictionary<string, string>() to save some space
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord2y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server
More Posts