dotnet / dotnet/fsharp

Hash function returns different result in F# and C#

Open
#2,103 4 comments 0 reactions 0 assignees View on GitHub
Area-Compiler-Optimization Feature Request
Dominant language
F#
Stars
4.3k
Forks
876
Avg merge
4d 11h
Merged PRs (30d)
131

Description

The Hash function returns always returns 0 for null values in C#, but in F# calling the hash function with a null value can result in a `NullReferenceException`.

I discovered it while working on https://github.com/Microsoft/visualfsharp/pull/2096. When the `GetHashCode` function is small enough in size, it causes the Hash function to return 0 in debug mode and not a `NullReferenceException` .

#### Repro steps

1. Create an F# library:

```
module Test

type Class1 = A |B

let test = Operators.hash (Unchecked.defaultof)
```

2. Create a C# console application with the following code:

```
using Microsoft.FSharp.Core;

namespace ConsoleApplication
{
class Program
{

static void Main(string[] args)
{
Test.Class1 a = null;
System.Console.WriteLine(Operators.Hash(a));
System.Console.WriteLine(Test.test);
}

}
}
```

3. Reference the F# library created in step 1 in the C# application created in step 2.

4. Build/Run the solution in Release or Debug configuration with any bitness.

#### Expected behavior

The same result is printed twice.

#### Actual behavior

The output is 0 for the first line followed by a `NullReferenceException`

#### Known workarounds

None.

#### Related information

Provide any related information

* Operating system: Windows 10
* Branch: F# 4.0 and master
* .NET Runtime, CoreCLR or Mono Version: .NET 4.6
* Editing Tools (e.g. Visual Studio Version): Visual Studio 2015

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.