Skip to content

Instantly share code, notes, and snippets.

@ctaggart
Last active August 29, 2015 14:11
Show Gist options
  • Save ctaggart/0c692d42b3bb8c19e229 to your computer and use it in GitHub Desktop.
Save ctaggart/0c692d42b3bb8c19e229 to your computer and use it in GitHub Desktop.
F# generics and overloads, oh my!
// attempted to add generic contraints
member inline x.AddWithOption<'T when 'T: not struct and 'T : null and 'T :> Object> (nm, op:Option<'T>) = x.AddWithValue (nm, toObj op) // Reference Types
member inline x.AddWithOption<'T when 'T: struct and 'T : (new : unit -> 'T) and 'T :> ValueType> (nm, op:Option<'T>) = x.AddWithValue (nm, toNullable op) // Value Types
// attempted C# style extension
// http://blogs.msdn.com/b/fsharpteam/archive/2013/06/27/announcing-a-pre-release-of-f-3-1-and-the-visual-f-tools-in-visual-studio-2013.aspx
[<Runtime.CompilerServices.Extension>]
static member inline AddWithOption (x:SqlParameterCollection, nm, op:Option<_>) = x.AddWithValue (nm, toObj op) // Reference Types
[<Runtime.CompilerServices.Extension>]
static member inline AddWithOption (x:SqlParameterCollection, nm, op:Option<_>) = x.AddWithValue (nm, toNullable op) // Value Types
// attempted C# style extensoin with generic constraints
[<Runtime.CompilerServices.Extension>]
static member inline AddWithOption<'T when 'T: not struct and 'T : null and 'T :> Object> (x:SqlParameterCollection, nm, op:Option<'T>) = x.AddWithValue (nm, toObj op) // Reference Types
[<Runtime.CompilerServices.Extension>]
static member inline AddWithOption<'T when 'T: struct and 'T : (new : unit -> 'T) and 'T :> ValueType> (x:SqlParameterCollection, nm, op:Option<'T>) = x.AddWithValue (nm, toNullable op) // Value Types
open System
open System.Data
open System.Data.SqlClient
// https://visualfsharp.codeplex.com/SourceControl/network/forks/dsyme/cleanup/contribution/7672#!/tab/changes
let toNullable option = match option with None -> System.Nullable() | Some v -> System.Nullable(v)
let toObj value = match value with None -> null | Some x -> x
type SqlDataReader with
member x.GetStringOption i = if x.IsDBNull i then None else x.GetString i |> Some
member x.GetDateTimeOption i = if x.IsDBNull i then None else x.GetDateTime i |> Some
type SqlParameterCollection with
member x.AddWithOption (nm, op:Option<_>) = x.AddWithValue (nm, toNullable op) // Value Type
member x.AddWithOption (nm, op:Option<_>) = x.AddWithValue (nm, toObj op) // Reference Type
Visual Studio 2013 Update 4, fsi
error FS0193: internal error: Index not found. (Exception from HRESULT: 0x80131124)
Visual Studio 2015 Preview, fsc
Error 1 A problem occurred writing the binary 'C:\tmp\Library2\obj\Debug\Library2.dll':
Error in pass2 for type Library, error: duplicate entry 'SqlParameterCollection.AddWithOption' in method table FSC 1 1 Library2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment