Home > Enterprise >  .NET 6 Preview 7: Runtime errors with generic math
.NET 6 Preview 7: Runtime errors with generic math

Time:10-09

I'm not sure if I've discovered a bug or if I'm doing something wrong, but this issue is not listed in the known issues of .NET 6:

I've got a unit test project with a single file that looks like this:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTest
{
    [TestClass]
    public class TestFoo
    {
        [TestMethod]
        public void Test()
        {
            var foo = new Foo();
        }
    }

    public class Foo : IAdditionOperators<Foo, Foo, Foo>
    {
        public static Foo operator  (Foo left, Foo right) => new();
    }
}

The test fails because of the following runtime error:

System.TypeLoadException: Virtual static method 'op_Addition' is not implemented on type 'UnitTest.Foo' from assembly 'UnitTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

But I very clearly have implemented the addition operator. In fact, when I build using dotnet build it compiles just fine until I remove the addition operator. Am I missing something?

Here is my project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <EnablePreviewFeatures>true</EnablePreviewFeatures>
    <LangVersion>preview</LangVersion>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.Runtime.Experimental" Version="6.0.0-preview.7.21377.19" />
  </ItemGroup>


  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.9.4" />
    <PackageReference Include="MSTest.TestAdapter" Version="2.2.3" />
    <PackageReference Include="MSTest.TestFramework" Version="2.2.3" />
    <PackageReference Include="coverlet.collector" Version="3.0.2" />
  </ItemGroup>

</Project>

CodePudding user response:

I was able to fix this error by moving Foo to a separate project and building that project using dotnet build from the command line. I then had to prevent VS from building the project again by referencing the dll directly from my test project.

My suspicion is that VS 2019 is not using the same compiler as dotnet build, and that the compiler in VS 2019 is failing to register the operator as an interface member to IAdditionOperators.

  • Related