Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 343
yljet Avatar asked Mar 22 '19 14:03

yljet


2 Answers

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.

like image 75
Tarmil Avatar answered Sep 20 '22 23:09

Tarmil


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.

like image 24
Magnetron Avatar answered Sep 19 '22 23:09

Magnetron