1

I have a class which models the format of the CSV being uploaded (I'm using the FileHelpers library):

[DelimitedRecord(",")]
public class CSVModel
{
    [FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
    public string Field1;
    [FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
    public string Field2;
}

Then I have a class to display the result of the upload after I've parsed the file row-by-row:

public class UploadResult
{
    public List<CSVModel> InvalidField;
    public List<CSVModel> Valid;
}

I won't go into detail about how I implement FileHelpers because it all works - a file can be uploaded successfully - it only breaks when I try add an instance of the CSV model to a list like so:

public static UploadResult ProcessCSV(CSVModel[] records)
{
    UploadResult uploadResult = new UploadResult();

    for (int i = 1; i < records.Length; i++)
    {
        CSVModel csvModel = records[i];

        // check stuff

        uploadResult.Valid.Add(csvModel); // this is where it breaks
    }

    return uploadResult;
}

The exception is giving me nothing more than null reference. What could I be doing incorrectly?

edit: When I debug, 'csvModel' is definitely not null when I try add it to the List

1
  • Is uploadResult.Valid null? Commented Jul 9, 2013 at 20:25

2 Answers 2

2

Valid is null, you have to initialize it:

public class UploadResult
{
    public List<CSVModel> InvalidField = new List<CSVModel>();
    public List<CSVModel> Valid = new List<CSVModel>();
}

or via constructor:

public class UploadResult
{
    public UploadResult()
    {
        InvalidField =  new List<CSVModel>();
        Valid =  new List<CSVModel>();
    }
    public List<CSVModel> InvalidField;
    public List<CSVModel> Valid;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Can only accept the answer in 12 minutes, but this solved it, thanks
1

You are initializing UploadResult but not the List properties. Try something like this:

UploadResult uploadResult = new UploadResult {
    InvalidField = new List<CSVModel>(),
    Valid = new List<CSVModel>()
};

1 Comment

If you do this and use UploadResult somewhere else, you'll need to remember to initialize the lists. @Tim's method is probably better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.