yield and anonymous methods

D

Dan Holmes

List<int> has as one of its constructors a collection so i thought
instead of creating a new class i would use an anonymous method


List<int> li = new List<int>(
delegate { yield return 5; yield return 9; })
);

That is not legal. there isn't really anything to fix here but just in
case some one else didn't know i thought i would post it.

dan

Is there any syntax to simulate this? I have tried {1, 2, 3} and other
sorts of array type initializers but i can't make anything work.
 
J

Jon Skeet [C# MVP]

Dan Holmes said:
List<int> has as one of its constructors a collection so i thought
instead of creating a new class i would use an anonymous method


List<int> li = new List<int>(
delegate { yield return 5; yield return 9; })
);

That is not legal. there isn't really anything to fix here but just in
case some one else didn't know i thought i would post it.

dan

Is there any syntax to simulate this? I have tried {1, 2, 3} and other
sorts of array type initializers but i can't make anything work.

You need new int[] {1, 2, 3}:

using System;
using System.Collections.Generic;

class Test
{
static void Main()
{
List<int> list = new List<int>(new int[]{1, 2, 3});

foreach (int i in list)
{
Console.WriteLine (i);
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top