Skip to content

Instantly share code, notes, and snippets.

@bent-rasmussen
Last active February 21, 2022 17:16
Show Gist options
  • Save bent-rasmussen/1c039ec2b5917b509e70ad697f8371f5 to your computer and use it in GitHub Desktop.
Save bent-rasmussen/1c039ec2b5917b509e70ad697f8371f5 to your computer and use it in GitHub Desktop.
How I learned to love the struct and stop worrying (part II)...
// Use the Test solution configuration and now test cases will fail if they are using '=' on structs.
#if STRUCT_EQ_CHECK
[<AutoOpen>]
#endif
module StructEqCheck =
type StructEqualityException() =
inherit exn()
let inline (=) (a: 'T) (b: 'T) =
let ty = typeof<'T>
if
ty.IsValueType // look for structs
&& (not ty.IsPrimitive) // except primitives
&& (not ty.IsEnum) // except enums
&& ty.IsAssignableTo(typeof<IEquatable<'T>>) // must be IEquatable<'T> otherwise fast track not possible
then
raise (new StructEqualityException())
// TODO also check types with nested structs
a = b
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AssemblyName>Foo</AssemblyName>
<Configurations>Debug;Release;Test</Configurations>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Test'">
<DefineConstants>STRUCT_EQ_CHECK</DefineConstants>
</PropertyGroup>
</Project>