C# version of VB.NET "AddRange" method w/generic collection

D

dgraper

Friends:

I'm an ex-VB programmer with a new job in an all C# shop. No problems
the past few months thinking/converting between the two, but I just
ran into a problem translating some working VB code from C#:

Dim enClr As System.Drawing.KnownColor
Dim clrs As New System.Collections.Generic.List (Of
System.Drawing.KnownColor)
clrs.AddRange(System.Enum.GetValues (enClr.GetType()))

I translated this to:

System.Drawing.KnownColor enClr;
System.Collections.Generic.List<System.Drawing.KnownColor> clrs =
new System.Collections.Generic.List<System.Drawing.KnownColor>();
clrs.AddRange(System.Enum.GetValues(enClr.GetType()));

But get error on line 3:

"Argument '1': cannot convert from 'System.Array' to
'System.Collections.Generic.IEnumerable<System.Drawing.KnownColor>'"

In the debugger it sure looks likes like
"System.Enum.GetValues(enClr.GetType())" is indeed returning a list of
type <System.Drawing.KnownColor>. I even ran the code thru a public
VB.NET to C# converter to see if I was missing anything, it gave me
exactly the same translation.

Can anyone see what I'm missing?

Thanks. - Dave
 
M

Martin Honnen

dgraper said:
System.Drawing.KnownColor enClr;
System.Collections.Generic.List<System.Drawing.KnownColor> clrs =
new System.Collections.Generic.List<System.Drawing.KnownColor>();
clrs.AddRange(System.Enum.GetValues(enClr.GetType()));

But get error on line 3:

"Argument '1': cannot convert from 'System.Array' to
'System.Collections.Generic.IEnumerable<System.Drawing.KnownColor>'"

In the debugger it sure looks likes like
"System.Enum.GetValues(enClr.GetType())" is indeed returning a list of
type <System.Drawing.KnownColor>. I even ran the code thru a public
VB.NET to C# converter to see if I was missing anything, it gave me
exactly the same translation.

With .NET 3.5 you can use Cast<T>() as follows:

System.Collections.Generic.List<System.Drawing.KnownColor>
clrs =
new
System.Collections.Generic.List<System.Drawing.KnownColor>();

clrs.AddRange(System.Enum.GetValues(typeof(System.Drawing.KnownColor)).Cast<System.Drawing.KnownColor>());
 
D

dgraper

Martin:

That was it. Thanks very much!

And thanks for such a rapid reply. I hope the question wasn't too
rudimentary. - Dave
 

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

Similar Threads


Top