开发者

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

I am trying to set a prope开发者_如何学运维rty 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.


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


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;


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

This line returns void.

Try:

var list = new List<Item>();
list.Add(item);
ItemListt.ItemList = list;


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

Does Add method return an instance of a list based class?

EDIT: No, see this link for documentation on List<T>.Add

EDIT2: Try writing this piece of code & see what is the return value of Add method.

List<Item> items = new List<Item>();
var modifiedList = items.Add(myItem);

You will see that, the code should fail at Add because it returns void.


So long as ItemList is instantiated on your usercontrol, you can just do UserControl.ItemList.Add(item)


The Add method doesn't return a reference to the list. You have to do this in two steps:

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

Alternatively use a local variable to hold the reference before you put it in the property:

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


For others who might come here from Googling the error:

Sometimes it's because you didn't finish writing a line but it compiles anyway and the error only shows up on the next line which can be confusing/misleading if you don't pay attention. Eg:

var foo = 33;
var bar = 

// Note that I never finished the assignation (got distracted, saved and it compiled)
//
// Some unrelated code returning "void" (another example would be List.Add)
await SomethingAsync(); // -> Error shows up here instead

Might save some of you all some headache trying to figure why "awaiting on my function" raises a "Cannot convert void to X", when really it's not the actual issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜