Skip to content

Visual Studio Code-Fix for generating GetHashCode results in OverflowException in checked assembly #24035

@yaakov-h

Description

@yaakov-h

Version Used:
Microsoft Visual Studio Enterprise 2017
Version 15.5.2

Steps to Reproduce:

  1. Create a new project with "Check for arithmetic overflow/underflow" enabled in the project Build settings
  2. Add the following class:
class Foo
{
    object bar;
    string baz;
}
  1. Place the cursor immediately after Foo
  2. Press Ctrl+. (period)
  3. Select "Generate Equals and GetHashCode()..."
  4. Create a new Foo object and call GetHashCode()

Full code:

using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            new Foo().GetHashCode();
        }
    }

    class Foo
    {
        object bar;
        string baz;

        public override bool Equals(object obj)
        {
            var foo = obj as Foo;
            return foo != null &&
                   EqualityComparer<object>.Default.Equals(bar, foo.bar) &&
                   baz == foo.baz;
        }

        public override int GetHashCode()
        {
            var hashCode = -1438245972;
            hashCode = hashCode * -1521134295 + EqualityComparer<object>.Default.GetHashCode(bar);
            hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(baz);
            return hashCode;
        }
    }
}

Expected Behavior:

The compiled program exits with code 0, printing no output.

Actual Behavior:

The compiled program crashes with a System.OverflowException:

System.OverflowException
  HResult=0x80131516
  Message=Arithmetic operation resulted in an overflow.
  Source=ConsoleApp1
  StackTrace:
   at ConsoleApp1.Foo.GetHashCode() in C:\temp\ConsoleApp1\ConsoleApp1\Program.cs:line 29
   at ConsoleApp1.Program.Main(String[] args) in C:\temp\ConsoleApp1\ConsoleApp1\Program.cs:line 9

I expect that the IDE code-fix should wrap the method body in an unchecked block when the assembly is checked.

Metadata

Metadata

Assignees

Labels

Area-IDEBugResolution-FixedThe bug has been fixed and/or the requested behavior has been implemented

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions