Plazza Sele
Plazza Sele

Reputation: 319

create an object and add a List<string>

I have a class Category that has:

public int id { get; set; }
public string catName { get; set; }
public List<string> subCat { get; set; }

I want to create a list like this:

List<Category> list = new List<Category>();
Category cat = new Category(){ 1 ,"Text", new List<string>(){"one", "two", "three"}};
list.Add(cat);

I get red error mark with this error message:

Cannot initialize type 'Category' with a collection initializer because it does not implement 'System.Collection.IEnumerable'

Any help would be much appriciated.

Upvotes: 1

Views: 723

Answers (4)

hYg-Cain
hYg-Cain

Reputation: 408

There are two possibilities to accomplish this. Basically your way of thinking is correct, but you have to change it a bit. One way is to make the constructor with Parameters so if you create an instance of this class it is generated with your Parameters.

 List<Category> list = new List<Category>();  
 Category cat = new Category( 1 ,"Text", new List<string>(){"one", "two","three" });  
 list.Add(cat);  

and as constructor

public Category(int  _id, string _name, List<string> _list){  
 id = _id;  
 catName = _name;  
  subCat = _list;
}  

Or

You add getter and setter methods to your class. Create an object and then set the variables

 List<Category> list = new List<Category>();  
 Category cat = new Category();  
 cat.id =  1;  
 cat.catName = "Text";  
 cat.subCat = new List<string>(){"one", "two","three" };  
 list.Add(cat);

Upvotes: 6

Jared Lovin
Jared Lovin

Reputation: 551

By the way you're initializing it, it thinks you're trying to implement a list. Do the following instead.

var category = new Category
{
    id = 1,
    catName = "Text",
    subCat = new List<string>(){"one", "two", "three"}
};

Upvotes: 13

Create object of Category and assign value

Category cat = new Category();
cat.id = 1,
cat.catName = "Text",
cat.subCat = new List<string>(){"one", "two", "three"};

list.Add(cat);

Upvotes: 2

BingBingBong
BingBingBong

Reputation: 88

What about using a normal constructor to perform that task? e.g.:

public Category(int id, String catName, List<String> subCat){
this.id = id;
this.catName = catName;
this.subCat = subCat;
}

use this in your Category class and acces the constructor by simply calling:

List<Category> list = new List<Category>();
Category cat = new Category(1, "Text", new List<String>(){"one", "two", "three"});

hope this helps you ;)

Upvotes: 1

Related Questions