Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3977808
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T04:58:04+00:00 2026-05-20T04:58:04+00:00

I have the following: foreach (ItemOption itemOption in p.Items.Select(e => e.ItemOption).GroupBy(e => e.Id)) {

  • 0

I have the following:

 foreach (ItemOption itemOption in p.Items.Select(e => e.ItemOption).GroupBy(e => e.Id))
  { // do some work on itemoptions }

This compiles.
However at runtime I get an Invalid Cast exception:

Unable to cast object of type ‘Grouping[System.String,MyNameSpace.ItemOption]’ to type ‘MyNameSpace.ItemOption’.

If I change the code to, e.g. a String as the type of the item :

 foreach (String itemOption in p.Items.Select(e => e.ItemOption).GroupBy(e => e.Id))
  { // do some work on itemoptions }

Then the compiler tells me the types are incompatible.

Why doesn’t the compiler flag the type incompatibility in the first code block?


I did some further investigation and found that, given the following code:

var foo = p.Items.Select(e => e.ItemOption).GroupBy(e => e.Id));
Type singleElementType = foo.ElementAt(0).GetType();

singleElementType is:

System.Linq.Lookup`2+Grouping[System.String, MyNamespace.ItemOption]


UPDATE
Following on from the answers I have put together a simpler case to demonstrate the issue

Given the objects:

interface IMyObj
{
    string Id;
}

class MyObj : IMyObj
{
    public string Id;
    public MyObj2 cg;
}

class MyObj2
{
}

This will fail at compile time

IEnumerable<MyObj> compileTimeFailList = new List<MyObj>()
foreach (MyObj2 myObj2 in compileTimeFailList.Where(x => x.Id != null))
{

and this will fail at run time

IEnumerable<IMyObj> runtimeFailList = new List<IMyObj>();
foreach (MyObj2 myObj2 in runtimeFailList.Where(x => x.Id != null))
{ 

The reason being that the objects in runtimeFailList may extend MyObj2 and this cannot be determined by the compiler.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T04:58:04+00:00Added an answer on May 20, 2026 at 4:58 am

    ItemOption is presumably not a sealed class (unlike System.String) so it’s possible that the result of p.Items.Select(...).GroupBy(...) would be implementations of IGrouping<...> which were also ItemOption values. The compiler can’t know, so it inserts an implicit cast. As string doesn’t implement IGrouping<...> and is sealed, the compiler can spot that that’s definitely a mistake.

    foreach has always included a cast where necessary. It’s a bit nasty, because it’s hidden… but without it, foreach would have been very painful to use pre-generics.

    Now as for why it’s actually wrong… each item in the result is going to be a grouping rather than an individual item. Let me know if you need more help working with the results.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code foreach (var rssItem in rss.Channel.Items) { // ... }
I have the following code: foreach (var control in this.Controls) { } I want
I have following foreach-loop: using System.IO; //... if (Directory.Exists(path)) { foreach(string strFile in Directory.GetFiles(path,
I have the following code: if ($_POST['submit'] == Next) { foreach($_POST['info'] as $key =>
I have following string String str = replace :) :) with some other string;
i have the following foreach. Inside you'll see a text box for quantity. At
I got a question. i have tha following foreach loop: {foreach from=$films item=film key=id}
I have the following code: foreach (string p in dirs) { string path =
I have the following code foreach (DataRowView dr in Data) { if (dr ==
I have the following code: foreach (Tuple<Point, Point> pair in pointsCollection) { var points

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.