Object reference not set to an instance of an object. error that I can't resolve
asp.net-mvc, c#
Solution
I suspect that previously you had:
Functions = new List<int> { 1,2, 3 }
That sets the property on the `Status` instance that's being constructed in your object initializer. Your current code, like this:
Functions = { 1,2,3 }
just calls `newObject.Functions.Add(1);` (etc) - that's not going to work while `Functions` is null, which it is by default.
Alternatives:
- Go back to explicitly creating a collection
Change your `Status` code to create the collection for you:
public class Status
{
public StatusEnum StatusEnum { get; set; }
public string DisplayAs { get; set; }
private readonly ICollection<int> functions = new List<int>;
public ICollection<int> Functions { get { return functions; } }
}
Problem
I had this code (this is just a snippet): ``` public static CpOfferInterfaceInfo Get() { return new CpOfferInterfaceInfo { Roles = new List<Role> { new Role { RoleType = RoleType.Cp, Statuses = new List<Status> { new Status { StatusEnum = StatusEnum.CpCreatedNew, DisplayAs = "Sent", Functions = { 1,2,3 } }, new Status { StatusEnum = StatusEnum.NcpDeclined, DisplayAs = "Declined", Functions = { 4 } }, ``` working fine earlier in the day and I changed one small thing (the Function = { 1, 3, 5 } clause) and now I get this error: Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: ``` Line 11: public static CpOfferInterfaceInfo Get() Line 12: { Line 13: return new CpOfferInterfaceInfo Line 14: { Line 15: Roles = new List<Role> ``` This is the C# class for Status: ``` public class Status { public StatusEnum StatusEnum { get; set; } public string DisplayAs { get; set; } public ICollection<int> Functions { get; set; } } ``` The code compiles but fails at run time. Anyone have any thoughts or experience with this? What can I change/try/test?