I have run into an error that I can not seem to fix. After doing some research on Stack Overflow it seemed as though the null coalescing operator would be the solution to my problem, but it has not helped. Here is the code that gives the error:
List<OperationsReviewLevelResult> results = new List<OperationsReviewLevelResult>();
foreach (var approval in OperationsReviewers.ApprovalItems)
{
var result = new OperationsReviewLevelResult();
result.ApproverName = approval.Results.FirstOrDefault().Name ?? "";
result.ReviewLevel = approval.Name;
result.Comment = approval.Results.FirstOrDefault().Comments ?? "";
results.Add(result);
}
When I run this code, I am getting:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Coming from the line result.ApproverName = approval.Results.FirstOrDefault().Name ?? "";
. I added the null coalescing operator to check for null values, but this is not fixing my problem. The error is because there is no Results
in approval so I assumed the FirstOrDefault
linq method would return the default value, and when it realizes the default value has a null value for Name
, it would use the null coalescing operator to return the ""
empty string on the right side of the operator.
Please let me know if I am missing something as I can not seem to understand why I am getting this error even when adding the null coalescing operator.
Edit: As suggested in a comment, looking at this post helped me learn more into why I received this error. Although the questions are a bit different, I highly recommend reading the answer for getting a full understanding of my problem.