core icon indicating copy to clipboard operation
core copied to clipboard

BadImageFormatException when calling Type.GetGenericTypeDefinition

Open IngvarKofoed opened this issue 7 years ago • 2 comments

General

Visual Studio 2019, 16.3.0 Preview 2.0 dotnet sdk: 3.0.100-preview8-013656 Windows 10 Enterprise x64, 1803

If I run the code below with debugger from Visual Studio, I get this exception:

System.BadImageFormatException: 'An attempt was made to load a program with an incorrect format. (0x8007000B)'

Here is the code

using System;

namespace StrangeError
{
    class Program
    {
        static void Main(string[] args)
        {
            GetResult<Boxed<int>>();
        }

        private static void GetResult<T>()
            where T : class
        {
            if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Boxed<>))
            {
                throw new NotImplementedException("The exceptions happens before this line");
            }

            throw new NotImplementedException("With the current code, this line is never reached");
        }
    }

    public class Boxed<T>
        where T : struct // Works if this constraint is removed
    {
        public Boxed(T value)
        {
            Value = value;
        }

        public T Value { get; }

        public bool Equals(Boxed<T>? other) =>
            false; // Implementation is not important, but this method has to be here

        public override bool Equals(object? obj) =>
            // false; Works if this is returned
            // true; Works if this is returned
            Equals(obj as Boxed<T>);

        public override int GetHashCode() =>
            Value.GetHashCode();
    }
}

It seems to be something with the Equals method, because it has to make a call to the specific Equals method. Also removing the generic type constraint on Boxed also make the code work again.

And here is the project config.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <LangVersion>8.0</LangVersion>
    <Nullable>enable</Nullable>
    <NullableContextOptions>enable</NullableContextOptions>
  </PropertyGroup>
</Project>

The code do not throw the BadImageFormatException if I remove the Nullable and NullableContextOptions elements.

Just let me know if you need any other informations :)

EDIT: Implementing the Equals method this way make the code run as expected.

public override bool Equals(object? obj)
{
    if (obj is Boxed<T> boxed)
    {
        return Equals(boxed.Value, Value);
    }
    else
    {
        return false;
    }
}

IngvarKofoed avatar Aug 21 '19 10:08 IngvarKofoed

Can confirm this fails in Preview 8. Thanks for the repro.

scalablecory avatar Aug 21 '19 21:08 scalablecory

This issue was moved to dotnet/roslyn#38183

scalablecory avatar Aug 21 '19 21:08 scalablecory