F# attributes, typeof, and "This is not a constant expression"

attributes, f#

Solution

You should address a circular type dependency introduced by forward usage of types in attributes. The snippet below shows how this can be done in F#:

// Compiles OK
[<AttributeUsage(AttributeTargets.All, AllowMultiple=true)>]
type XmlInclude(t:System.Type) =
   inherit System.Attribute()

[<XmlInclude(typeof<Car>)>]
[<XmlInclude(typeof<Truck>)>]
type Vehicle() = class end
and Car() = inherit Vehicle()
and Truck() = inherit Car()

Problem

EDIT: Added a more complete example, which clarified the problem. Some .NET attributes require a parameter of type `Type`. How does one declare these parameters in F#? For example, in C# we can do this: ``` [XmlInclude(typeof(Car))] [XmlInclude(typeof(Truck))] class Vehicle { } class Car : Vehicle { } class Truck : Vehicle { } ``` But, in F# the following... ``` [<XmlInclude(typeof<Car>)>] [<XmlInclude(typeof<Truck>)>] type Vehicle() = class end type Car() = inherit Vehicle() type Truck() = inherit Car() ``` ...results in a compiler error: This is not a constant expression or valid custom attribute value.

Original source