Why this line throws an error?

Camillia
Camillia used Ask the Experts™
on
Practicing interview questions. Why does the second line throws an error? Is it because an explicit conversation is needed? I read about ValueTypes but still don't understand why it errors out..


IEnumerable<object> objects = new List<string>();
IEnumerable<ValueType> v =  objects; //*** error here.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
AndyAinscowFreelance programmer / Consultant
Commented:
You could cast it and it will compile.
eg.
            IEnumerable<object> objects = new List<string>();
            IEnumerable<ValueType> v = (IEnumerable<ValueType>)objects;
compiles.

Note it will then fail at run time, at least in this particular case.

A reason being is the following does not work
            IEnumerable<ValueType> objects = new List<string>();

Because a string is not a ValueType
Commented:
If on the other hand, you meant to do this by insinuating that ValueType is the type of the original list's T parameter.  Then you wont get a runtime error as pointed out by Andy above.  In order to accomplish this, you would do something like this:
IEnumerable<object> objects = new List<string>();
IEnumerable<string> values = objects as IEnumerable<string>;
// IEnumerable<string> values = (IEnumerable<string>)objects; // This is the same thing as above

Open in new window

Proof of concept -
using System;
using System.Collections.Generic;

namespace EE_Q29137538
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable<object> objects = new List<string> { "A", "New", "List" };
            IEnumerable<string> values = objects as IEnumerable<string>;
            Console.WriteLine(string.Join(" ", values));
            Console.ReadLine();
        }
    }
}

Open in new window

Which produces the following output -Capture.PNG-saige-
I tried casting but I did it wrong. These are the options they gave me (interviewer let me take the questions with me)

Their question was "why is there an error when compiling the code". Looking at your explanation...it's the last one...explicit conversion is needed...correct?

b2.png
Freelance programmer / Consultant
Commented:
To make it compile one must use a cast.  (Note it doesn't make the code actually work.)
So it certainly looks like the final choice is the one they wanted as the answer.
Thanks, Andy

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial