1

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.

2

4 Answers 4

13

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"}
};
Sign up to request clarification or add additional context in comments.

Comments

6

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);

2 Comments

Hi hYg-Cain; could you add some context to your answer, for example some explanation of how your code differs from the code in the original question, and what it is about these changes which will provide a solution?
Sure sorry that i didn't took the time in first place.
2

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);

Comments

1

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 ;)

Comments

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.