Pages

Thursday, April 12, 2012

Auto-Implement Property and Constructor do binding in Beta

From the previous F# auto-implemented property post, that property declaration shortcut does provide convenience to developer. However, when it combines with the constructor, there are something interesting.


type A() as this =
    do this.Bar()
    // let Y@ = 0
    member this.Bar() = printfn "In F()"
    //member val Y = 0 with get,set

let a = new A()

The code above works. But when you uncomment the auto-implemented property. The code compiles but will spite out an error at the printfn.




type A() as this =
    do this.Bar()

    // let Y@ = 0
    member this.Bar() = printfn "aaa"  //error!
    member val Y = 0 with get,set

let a = new A()


System.InvalidOperationException occurred
  HResult=-2146233079
  Message=The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.
  Source=FSharp.Core
  StackTrace:
       at Microsoft.FSharp.Core.LanguagePrimitives.IntrinsicFunctions.FailInit()
  InnerException: 
I was confused by the error message at first glance. where is the object or value needs to be initialized? Actually this error says the A class cannot be initialized. If you want to ask why?

The auto-implemented property put a hidden backend field right after the do binding section. The commented out line after the do this.Bar() is the hidden code. As a result, when do binding is trying to execute this.Bar(), there is still one field, Y@,  needs to be initialized. Because one of the fields needs to be initialized, the instance is not initialized. That's how you get this error. 


This exists in Beta. So if you run into this problem, do not panic. you can try to use the old way to define the property.


2 comments:

Anonymous said...

Thanks for sharing information about Auto-Implement Property and Constructor do binding in Beta.Good work keep it up !!
Auto Service centre

Nicolas said...

thks for sharing. did you raise that t othe attention of the fsharp team ? it does not seem like a wanted behaviour.