Skip to content

Enumerable.Empty<T> in .NET Core 3.0 cannot be cast to IList<T> #27552

@natemcmaster

Description

@natemcmaster

Yes, casting is bad...so we probably shouldn't do this, but is it reasonable to expect this to keep working?

using System;
using System.Collections.Generic;
using System.Linq;

namespace cast_to_list
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"There are {GetBugs().Count} bugs in casting Enumerable.Empty<T> to IList<T>");
        }

        private static IList<int> GetBugs()
        {
+           return (IList<int>)Enumerable.Empty<int>();
        }
    }
}
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp2.1;netcoreapp3.0</TargetFrameworks>
  </PropertyGroup>

</Project>

The cast works in .NET Core 2.1, but not 3.0. In 3.0, it fails with:

Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.Linq.EmptyPartition`1[System.Int32]' to type 'System.Collections.Generic.IList`1[System.Int32]'.

I'm using .NET Core 2.1.5 and 3.0.0-preview1-27003-04.

image

cc @rainersigwald

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions