This is related to this question.
I’d like to create a generic wrapper class:
public abstract class Wrapper<T>
{
internal protected T Wrapped { get; set; }
}
With the following extensions:
public static class WrapperExtensions
{
public static W Wrap<W,T>(this T wrapped) where W:Wrapper<T>,new()
{
return new W {Wrapped = wrapped};
}
public static T Unwrap<T>(this Wrapper<T> w)
{
return w.Wrapped;
}
}
Now assume a concrete Wrapper:
public class MyIntWrapper : Wrapper<int>
{
public override string ToString()
{
return "I am wrapping an integer with value " + Wrapped;
}
}
I would like to call the Wrap extension like this:
MyIntWrapper wrapped = 42.Wrap<MyIntWrapper>();
This is not possible because in c# we need to provide both type arguments to the Wrap extension.
(it’s all or nothing)
Apparently partial inference is possible in F#.
How would the above code look in F#?
Would it be possible to use it from C#?
Apparently partial inference is possible in F#.
Yes, only W would need to be specified in your example. T will be inferred.
How would the above code look in F#?
And you can call Wrap from F# interactive this way
In my opinion this is not very idiomatic in F#, I would rather use Discriminated Unions and Pattern Matching for wrapping/unwrapping but I don’t know exactly what’s your specific case.
Would it be possible to use it from C#?
Sure, but if you call
Wrapfrom C# you’re back to C# type inference and will have to specify the second type parameter.