hubFS: THE place for F#

. . . are you on The Hub?
Welcome to hubFS: THE place for F# Sign in | Join | Help
in Search

ISerializable and constructed classes

Last post 07-03-2009, 8:46 by DannyAsher. 2 replies.
Sort Posts: Previous Next
  •  07-02-2009, 12:08 11173

    ISerializable and constructed classes


    Hi,

    I'm trying to implement a simple TcpChannel between 2 AppDomains and need to pass an object (by value) from one to another. The object is a SerializableDictionary but also needs a default constructor and a constructor of type:

    protected SerializableDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { }

    I can't seem to be able to get both constructors into an F# type.

    open System
    open System.Collections.Generic
    open System.Xml
    open System.Xml.Serialization
    open System.Runtime.Serialization

    [<Serializable>]

    [<XmlRoot("dictionary")>]

    type SerializableDictionary<'TKey, 'TValue>(info: SerializationInfo, context: StreamingContext) =
        inherit Dictionary<'TKey, 'TValue>(info, context)
        new() = SerializableDictionary<'TKey, 'TValue>(null, new StreamingContext())


    causes a run-time exception:

    ERROR: Object reference not set to an instance of an object.

    I believe that F# requires all contructors to call the 'primary' contructor, but this doesn't seem correct here. Is it possible for an F# type to contain these two constructors?

    All help much appreciated,

    Danny
  •  07-02-2009, 12:47 11174 in reply to 11173

    Re: ISerializable and constructed classes

    If you want two different constructors in a derived class to call into two different constructors in a base class, then you must use the 'explicit' class syntax, where there are no parens after the type/inherit declaration, and instance variables use 'val'.

    http://msdn.microsoft.com/en-us/library/dd469494(VS.100).aspx

    Here's an example:



    [<Serializable>]
    [<XmlRoot("dictionary")>]
    type SerializableDictionary<'TKey, 'TValue> =
        inherit Dictionary<'TKey, 'TValue>
        val anotherInstanceVar : int
        new(info: SerializationInfo, context: StreamingContext) = {inherit Dictionary<'TKey, 'TValue>(info,context); anotherInstanceVar = 4}
        new() = {inherit Dictionary<'TKey, 'TValue>(); anotherInstanceVar = 0}

    This is one of the very few cases where you need to use this 'explicit' syntax rather than the preferred syntax involving a primary constructor.

  •  07-03-2009, 8:46 11177 in reply to 11174

    Re: ISerializable and constructed classes


    Thanks Brian - that works nicely.

    regards,

    Danny
View as RSS news feed in XML
Powered by Community Server, by Telligent Systems