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

  • SEARCH
  • Home
  • 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 1075159
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T21:14:06+00:00 2026-05-16T21:14:06+00:00

I have a collection of nullable ints. Why does compiler allows to iteration variable

  • 0

I have a collection of nullable ints.

Why does compiler allows to iteration variable be of type int not int? ?

        List<int?> nullableInts = new List<int?>{1,2,3,null};
        List<int> normalInts = new List<int>();


        //Runtime exception when encounter null value
        //Why not compilation exception? 
        foreach (int i in nullableInts)
        {
         //do sth
        }

Of course I should pay attention to what I iterate through but it would be nice if compiler reprimanded me:) Like here:

        foreach (bool i in collection)
        {
          // do sth 
        }

       //Error 1 Cannot convert type 'int' to 'bool'
  • 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-16T21:14:06+00:00Added an answer on May 16, 2026 at 9:14 pm

    Update

    OK, originally I said “the compiler adds casts to a foreach loop.” This isn’t strictly accurate: it won’t always add casts. Here’s what’s really happening.

    First of all, when you have this foreach loop:

    foreach (int x in collection)
    {
    }
    

    …here is the basic outline (in pseudo-C#) of what the compiler creates:

    int x;
    [object] e;
    try
    {
        e = collection.GetEnumerator();
        while (e.MoveNext())
        {
            x = [cast if possible]e.Current;
        }
    }
    finally
    {
        [dispose of e if necessary]
    }
    

    What? I hear you saying. What do you mean by [object]?”

    Here’s what I mean. The foreach loop actually requires no interface, which means it’s actually a little bit magical. It only requires that the type of object being enumerated exposes a GetEnumerator method, which in turn must provide an instance of some type that provides a MoveNext and a Current property.

    So I wrote [object] because the type of e does not necessarily have to be an implementation of IEnumerator<int>, or even IEnumerator — which also means it doesn’t necessarily have to implement IDisposable (hence the [dispose if necessary] part).

    The part of the code we care about for the purpose of answering this question is the part where I wrote [cast if possible]. Clearly, since the compiler doesn’t require an actual IEnumerator<T> or IEnumerator implementation, the type of e.Current cannot be assumed to be T, object or anything in between. Instead, the compiler determines the type of e.Current based on the type returned by GetEnumerator at compile time. Then the following happens:

    1. If the type is the type of the local variable (x in the above example), a straight assignment is used.
    2. If the type is convertible to the type of the local variable (by which I mean, a legal cast exists from the type of e.Current to the type of x), a cast is inserted.
    3. Otherwise, the compiler will raise an error.

    So in the scenario of enumerating over a List<int?>, we get to step 2 and the compiler sees that the List<int?>.Enumerator type’s Current property is of type int?, which can be explicitly cast to int.

    So the line can be compiled to the equivalent of this:

    x = (int)e.Current;
    

    Now, what does the explicit operator look like for Nullable<int>?

    According to Reflector:

    public static explicit operator T(T? value)
    {
        return value.Value;
    }
    

    So the behavior described by Kent is, as far as I can tell, simply a compiler optimization: the (int)e.Current explicit cast is inlined.

    As a general answer to your question, I stick by my assertion that the compiler inserts casts in a foreach loop where needed.


    Original Answer

    The compiler automatically inserts casts where needed in a foreach loop for the simple reason that before generics there was no IEnumerable<T> interface, only IEnumerable*. The IEnumerable interface exposes an IEnumerator, which in turn provides access to a Current property of type object.

    So unless the compiler performed the cast for you, in olden times, the only way you could’ve used foreach would’ve been with a local variable of type object, which obviously would’ve sucked.

    *And actually, foreach doesn’t require any interface at all — only the GetEnumerator method and an accompanying type with a MoveNext and a Current.

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

Sidebar

Related Questions

I have a collection of objects to which I'd like to just add a
I have a collection of classes that inherit from an abstract class I created.
I have a collection of non-overlapping rectangles that cover an enclosing rectangle. What is
We have a collection of commercial MFC/C++ applications which we sell using Stingray Objective
I have a collection of classes that I want to serialize out to an
I have a collection of elements that I need to operate over, calling member
I have a collection of Boost unit tests I want to run as a
I have a collection of unmanaged dlls with a C# wrapper around them that
I have a collection of custom entity objects one property of which is an
I have a collection of data stored in XDocuments and DataTables, and I'd like

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.