Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Cannot implicitly convert type 'void' to 'System.Collections.Generic.List'

Tags:

c#

asp.net

I am trying to set a property of my .ascx controls from an .aspx using that control.

So in one of my .aspx which has this control in it, I have the following code trying to set the ItemsList property of my embedded .ascx:

Item item = GetItem(itemID);
myUsercontrol.ItemList = new List<Item>().Add(item);

The property in the .ascx that I'm trying to set looks like this:

public List<Item> ItemsList
{
   get { return this.itemsList; }
   set { this.itemsList = value; }
}

Error: Cannot implicitly convert type 'void' to 'System.Collections.Generic.List'

So I don't get where it's getting void as part of the property?...weird.

like image 503
PositiveGuy Avatar asked Dec 08 '09 17:12

PositiveGuy


3 Answers

You can't do that because the Add function returns void, not a reference to the list. You can do this:

mycontrol.ItemList = new List<Item>();
mycontrol.ItemList.Add(item);

or use a collection initializer:

mycontrol.ItemList = new List<Item> { item };
like image 95
Mark Byers Avatar answered Nov 05 '22 04:11

Mark Byers


After creating the List<Item> you're immediately calling Add on it, which is a method returning void. This cannot be converted to the type of ItemList.ItemList.

You should do this instead:

var list = new List<Item>();
list.Add(item);
ItemList.ItemList = list;
like image 24
Lee Avatar answered Nov 05 '22 03:11

Lee


new List<Item>().Add(item);

This line returns void.

Try:

var list = new List<Item>();
list.Add(item);
ItemListt.ItemList = list;
like image 1
mYsZa Avatar answered Nov 05 '22 05:11

mYsZa