Using F# type providers how do you implement a base constructor call as part of the constructor definition

StackOverflow https://stackoverflow.com/questions/22708114

  •  23-06-2023
  •  | 
  •  

Question

What Im trying to do is create a provided type that calls its base constructor like this in C#:

public class SubclassController : BaseClass
{
    public SubclassController (IntPtr handle) : base (handle)
    {}
}

The closest I can currently get is this:

public sealed class SubclassController : BaseClass
{
    public SubclassController (IntPtr handle)
    {
        this;
        base..ctor (handle);
    }

Which although having the same functionality is not entirely the same.

The code I am using to build the ProvidedConstructor is as follows:

let providedConstructor = ProvidedConstructor([ProvidedParameter("handle", typeof<IntPtr>)])
let ctorInfo = typeof<SubclassController>.GetConstructor(BindingFlags.Public ||| BindingFlags.Instance, null, [|typeof<IntPtr>|], null)
providedConstructor.BaseConstructorCall <- fun args -> ctorInfo, args
providedConstructor.InvokeCode <- fun args -> <@@ () @@>
Was it helpful?

Solution

It was actually a bug in ProvidedTypes.fs which has now been fixed in the latest version. It is available from the usual place at codeplex thanks to @desco

So this code is actually all thats needed for a correctly formed base constructor call:

let providedConstructor = ProvidedConstructor([ProvidedParameter("handle", typeof<IntPtr>)])
let ctorInfo = typeof<SubclassController>.GetConstructor(BindingFlags.Public |||         BindingFlags.Instance, null, [|typeof<IntPtr>|], null)
providedConstructor.BaseConstructorCall <- fun args -> ctorInfo, args
providedConstructor.InvokeCode <- fun args -> <@@ () @@>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top