Search code examples
c#serializationcollectionsdatacontract

Deserializing with DataContract Collection<Class> to derived Class


The title is a bit confusing, hopefully someone maybe know's a better fitting title for my problem.

I am trying to create a class which derives from Collection<Classname> to implement an easy way to save and loading Configuration files. Writing to file is no problem, but I am not able to implement the deserialze function. I am unsure how to assign the deserialized content back to my instance.

Current approach:

[DataContract(Name = "Configurations", Namespace = "")]
public class Configurations : Collection<Configuration>
{
    internal void SerializeToBinaryFile(string path)
    {
        Helper.DumpObjectToBinaryFile(this, path);
    }

    internal void DeserializeFromBinaryFile(string path)
    {
       // Getting Error:
       // This expression can not be used as an assignment target
       this = Helper.GetObjectFromBinaryFile<Collection<Configuration>>(path);
    }
}

I am familiar with this.Add([Configuration]) but this just gives the opportunity to insert one item. I thought about using a foreach(Configuration c in temporaryObject and add them one by one but this can't be the best solution.

Thanks for any hint!

Edit 1:

I've added the foreach iteration for adding the Configurations

    internal void DeserializeFromBinaryFile(string path)
    {
        foreach (var c in Helper.GetObjectFromBinaryFile<Collection<Configuration>>(path))
        {
            Add(c);
        }
    }

This seems to work fine. Does someone know a better pattern?


Solution

  • You cannot assign to new instance of class to "this" regardless if you are doing de-serialization or something else. Code bellow just uses new constructor and doesn't work either. Basically, you do have different 2 instances of class in memory at that point.

    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }
    
        public void CreatePoint(int x, int y)
        {
            // Doesn't work either
            this = new Point();
        }
    }
    

    You have to do this outside of the body of the class, so rather make static deserialization method:

    [DataContract(Name = "Configurations", Namespace = "")]
    public class Configurations : Collection<Configuration>
    {
        internal void SerializeToBinaryFile(string path)
        {
            Helper.DumpObjectToBinaryFile(this, path);
        }
    
        internal static Configurations DeserializeFromBinaryFile(string path)
        {
            return Helper.GetObjectFromBinaryFile<Collection<Configuration>>(path);
        }
    }