Oztaco
Oztaco

Reputation: 3459

Lists inside classes?

I have a List of strings called Names in a class called data. The code for the list looks like this:

public class data {
  public List<string> Names = new List<string>();
  Names.Add("C1");
}

When I run the program, the code fails on the line with names.Add("C1");

[edit] The error message given is "The type or namespace Names could not be found (Are you missing a using directive or an assembly reference?)"

Upvotes: 1

Views: 1352

Answers (2)

Kirk Broadhurst
Kirk Broadhurst

Reputation: 28728

If your class looks like this

public class MyClass
{
    public List<string> Names = new List<string>();
    Names.Add("C1");
}

then that is indeed illegal. The class level is for defining members, and is not for calling methods (the Add statement). You instead need to call the Add method inside a method or constructor.

public class MyClass
{
    public List<string> Names = new List<string>();

    public MyClass()
    {
        Names.Add("C1");
    }
}

or alternatively, simply initialize the list with that value:

public List<string> Names = new List<string>() { "C1" };

Upvotes: 1

Gary.S
Gary.S

Reputation: 7131

I am going to take a shot in the dark and guess your class looks like this:

public class data
{
    public List<string> Names = new List<string>();
    Names.add("C1");
}

In this case the problem is infact the add method is not a member or method declaration and cannot exist where it is. One solution would be to add that in the constructor:

public class data
{
    public List<string> Names = new List<string>();

    public data()
    {
        Names.Add("C1");
    }
}

Another option is to add it to the declaration:

public List<string> Names = new List<string>(){ "C1" };

Upvotes: 6

Related Questions