Hi,
you can write the following:

1
2
3
4
5
 
type DerivedCollection() as this =
  inherit CollectionKind()
  let isActive = new BoolKind(this)
  member x.IsActive = isActive
By on 11/14/2008 8:27 AM ()

Thanks for the quick reply. I tried your suggestion and I get a blue squiggly over the 'this' in BoolKind(this) with the following error:

Recursive references to the object being defined will be checked for initialization soundness at runtime through the use of a delayed reference. Consider placing self-references within 'do' statements after the last 'let' binding in the construction sequence.

When I run I get a null reference exception on the same line.

Any ideas? - Jake

By on 11/14/2008 9:01 AM ()

Ahh, sorry!
The problem was that the code used 'this' before the class was fully initialized. This could lead to errors (where some fields would have 'null' values), so F# tries to prevent that - and shows the warning you've seen.

To workaround this, you can use mutable values and initialize them once the class is constructed. You can use 'option' type during the initialization to make sure that all possible errors will be handled properly:

1
2
3
4
5
6
7
8
9
10
11
12
13
 
type CollectionKind() =
  member x.A = "ZZ"

type BoolKind(c:CollectionKind) =
  do printfn "%s" c.A
        
type DerivedCollection() as this =
  inherit CollectionKind()
  let mutable isActive = None
  do 
    isActive <- Some(BoolKind(this))
  member x.IsActive = match isActive with | Some(v) -> v | _ -> failwith "Wrong initialization!"

An alternative "unsafe" way is to use the DefaultValue attribute:

1
2
3
4
5
6
7
8
9
10
11
 
type DerivedCollection() as this =
  inherit CollectionKind()
  
  // Value will be 'null' until the class is constructed
  [<DefaultValue(false)>]
  val mutable isActive : BoolKind 
  do 
    this.isActive <- new BoolKind(this)
    
  member x.IsActive = this.isActive

T.

By on 11/14/2008 9:20 AM ()

Works. Thanks!

By on 11/14/2008 12:18 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper