Reputation: 11019
I have a created an object that will hold errors encountered as well as a boolean field to indicate if any errors were present at all. The class looks like this.
public class ValidationResult
{
public bool IsValid{ get; set; }
public List<string> Errors { get; set; }
}
I go to use an instance of this class in a validation method as such
public class ValidationService
{
// This instance will hold the errors if there are any
ValidationResult myValidationResult = new ValidationResult();
public void ValidationMethod()
{
// Validation takes place here
...
// Some errors occurred to lets add then to the instance of the ValidationResult object
myValidationResult.IsValid = false;
myValidationResult.Errors.Add("An error occurred here are the details");
}
}
The problem is that the Errors collection in the instance myValidationResult
is null? Why is this? I created an instance of the class and the boolean property IsValid
is available, yet the Errors
collection is null
.
Upvotes: 0
Views: 46
Reputation: 7803
You must initialize your Errors property:
public class ValidationResult
{
public ValidationResult()
{
Errors = new List<string>();
}
public bool IsValid{ get { return (Errors.Count() == 0); } }
public List<string> Errors { get; set; }
}
Upvotes: 3
Reputation: 9679
Only value types are initialized per default. Your List<string>
is a reference type and it does have it default value - null.
Look here for a little bit more information:
https://msdn.microsoft.com/en-us/library/aa691171(v=vs.71).aspx
Upvotes: 2