Skip to content

Allow defining covariant/contravariant type parameters for use in other .NET languages #1450

@IS4Code

Description

@IS4Code

I propose we have a way to produce (i.e. not necessarily consume from within F#) type parameters that are covariant/contravariant, per .NET's rules (allowed only in input/output positions, respectively).

Custom attributes could be used for this purpose, such as:

type IEnumerable<[<Out>] 'T> =
  abstract member GetEnumerator : unit -> IEnumerator<'T>
and IEnumerator<[<Out>] 'T> =
  abstract member Current : 'T with get

I chose to abuse InAttribute and OutAttribute for this purpose here, since .NET disallows them on type parameters (F# would have to treat them as allowed) and they look similar to C#'s syntax and thus are broadly understandable. Of course different attributes could be used for this purpose too.

The existing way of approaching this problem in F# is none; maybe via (unsafe) IL rewriting to add the necessary flags.

Pros and Cons

The advantages of making this adjustment to F# are parity with other .NET languages in terms of quality of type hierarchies, improving interoperability with such languages.

The disadvantages of making this adjustment to F# are having a feature that cannot be used from within F# itself (in company with CLIMutable etc.)

Extra information

Estimated cost (XS, S, M, L, XL, XXL): S

Related suggestions: #162

Affidavit (please submit!)

Please tick these items by placing a cross in the box:

  • This is not a question (e.g. like one you might ask on StackOverflow) and I have searched StackOverflow for discussions of this issue
  • This is a language change and not purely a tooling change (e.g. compiler bug, editor support, warning/error messages, new warning, non-breaking optimisation) belonging to the compiler and tooling repository
  • This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it
  • I have searched both open and closed suggestions on this site and believe this is not a duplicate

Please tick all that apply:

  • This is not a breaking change to the F# language design
  • I or my company would be willing to help implement and/or test this

For Readers

If you would like to see this issue implemented, please click the 👍 emoji on this issue. These counts are used to generally order the suggestions by engagement.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions