Why this line of code is not correct? difference between them?

Camillia
Camillia used Ask the Experts™
on
I'm reviewing some interview questions. Why is the first one wrong and the second one correct?

            IEnumerable<string> objects1 = new List<object>(); //*** not correct

            IEnumerable<object> objects = new List<string>(); //correct
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Freelance programmer / Consultant
Commented:
The first line you are casting a general object (eg.  string, Form.....) to a string and the compiler is alerting you to a mistake in your code.
The second line is fine at compile time because because a string is an object.

Inheritance, a string class is based on a object class.  Not the other way round.

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