Dave
Dave

Reputation: 2386

Using records with generics that require a default constructor

I'd like to use a record with a data structure that requires its types to have a default constructor. Unfortunately this results in a compile time error.

Aside from changing the data structure (not possible here). Or changing the record to a type (would require adding in type annotations ever where) what options do you have in this type of scenario?

I suppose one could wrap the record inside a struct, but that feels like hack.

Upvotes: 2

Views: 1560

Answers (2)

latkin
latkin

Reputation: 16812

This appears to have been fixed in F# 3.1. Consider this code:

[<CLIMutable>]
type R = {a : int}

let f<'a when 'a : (new : unit -> 'a)>() = new 'a()

let r = f<R>()

In F# 3.0 (VS 2012), you get an error on the last line - error FS0001: A generic construct requires that the type 'R' have a public default constructor

But it works in F# 3.1 (not RTM yet, but public pre-release was earlier this week)

Upvotes: 7

Joel Mueller
Joel Mueller

Reputation: 28764

Try adding the CLIMutable attribute to your record.

Upvotes: 7

Related Questions