yljet
yljet

Reputation: 81

Are F#'s generic member constraints possible within C#?

F# allows constraining generic types on the type's members, similar to:

    type ClassWithMemberConstraint<'T when 'T : (static member StaticProperty : unit)> =
    class end

This can be very handy, especially since the CLR doesn't allow defining interfaces with static members. Because F# allows such a constraint, I'm guessing it means that the CLR allows for generic member constraints as well, but from what I can tell, this isn't possible in C#.

Are there any ways to express this behavior in C#?

Upvotes: 8

Views: 294

Answers (2)

Tarmil
Tarmil

Reputation: 11362

Because F# allows such a constraint, I'm guessing it means that the CLR allows for generic member constraints as well

Unfortunately, no. F# member constraints are implemented "outside of IL", so to speak. Functions with member constraints are not compiled into IL methods, but instead are stored in the F# metadata in the assembly. Then, every time such a function is called, its code is inlined at the call site with the generic type specialized to what is used in that particular place. That's why all functions with member constraints must be marked inline, by the way.

Upvotes: 4

Magnetron
Magnetron

Reputation: 8543

Well, comparing F# constraints with C# ones we can see that there are no equivalent of F# Explicit Member Constraint in C#.

What you possibly can do is define an abstract class and constrain on that, so your classes must inherit from that abstract class. Note, however, that the inherited classes will use the same static object of the parent abstract class.

Upvotes: 2

Related Questions