F# SRTP vs C# Interfaces

beginners
#1

Sorry if this is not the place for this kind of questions or topics. I’m learning about SRTP and their usage. It seems to me that they’re similar to the old OO (C#) interfaces or to abstract types, by which one could also express some constraints (method signatures) on an entity…
What am I missing?

0 Likes

#2

Statically-resolved type parameters work on types and do it at compile-time, unlike interfaces which constrain instances at run-time. With SRTPs you get an error at compile time, with interfaces you get InvalidCastException (or null, depending on how you do it).

0 Likes

#3

My idea for the comparison is doing something like the following on C# side

https://dotnetfiddle.net/vz7TeU

I don’t see any cast in the relevant points for the comparison.

More importantly, C# is statically typed and an interface represents a contract on types (i.e. classes in C#) that the C# compiler verifies at compile time.

0 Likes

#4

For a more elaborate F# comparison using abstract types vs SRTP switch between master and srtp branch for

0 Likes

#5

SRTP gives you ability to use not only your types but any types suitable to specified constraints.

Let’s image that there is a type MyType2:

public class MyType2 
{
    public bool DoIt() => false;
}

It doesn’t implement interface IVM so you can’t pass it to the function DSL. But in F# you can create such function with SRTP.

0 Likes

#6

Hi @FoggyFinder,
happy to find you here!
[ sorry for the off topic but I can’t stand the unfriendly C# community on SO so I periodically delete my profile there after every time I try to communicate, even if I’ve to admit that there are informed professionals.
Back on topic now]
Your reasoning exactly follows my example, so your reply is very accurate.
For MyType2 I would have to write MyWrapper2 as well as I did for MyType.
So SRTP 1 - Interface 0 :slight_smile:
Then enters MyType3 with MakeIt instead of DoIt. No problem for MyWrapper3 but it’s an issue on SRTP side.
So SRTP 1 - Interface 1 :wink:

0 Likes