Dean Dean - 3 months ago 10
C# Question

Object reference is required for non-static field. List<>

I'm a little confused about this fairly typical error. My code is as below. I am trying to add items to a list.

The compiler is saying I need an object reference for non-static field, but I can't make the class static because I am not returning a value...?

public class ApplicantData
{
public string Salutation { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
}

public class ApplicantList : List<ApplicantData>
{
public void Add(string salutation, string firstName, string lastName)
{
var data = new ApplicantData
{
Salutation = salutation,
FirstName = firstName,
LastName = lastName

};
this.Add(data);
}
}


The above is called via:

List ApplicantsDetailsData = ApplicantList.Add(salutation, firstname, lastname);


I'm sure the answer must be obvious... (!)

Answer

You need an instance of a list to add things to it. Right now you only have the concept of a list. You have zero lists. For example:

var list = new ApplicantList();
list.Add("foo", "bar", "blap");

However, usually it is a bad / confusing move to subclass List<T>, IMO.