Last active
February 21, 2022 17:16
-
-
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)...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Resources