Eric J.
Eric J.

Reputation: 150138

Can a readonly field be initialized when using DataContractSerializer?

DataContractSerializer does not call a constructor or invoke field initializers when deserializing:

DataContractSerializer doesn't call my constructor?

Field Initializer in C# Class not Run when Deserializing

Setting the initial value of a property when using DataContractSerializer

Is it possible to initialize a readonly field after object deserialization? Must I abandon that language feature in order to use DataContractSerializer?

Upvotes: 10

Views: 2308

Answers (3)

ForceMagic
ForceMagic

Reputation: 6379

I found a clean way to achieve what you are looking for without breaking your design.

Using this method will ensure that your constructor will be called and your readonly field properly set.


What you need is to actually serialize and deserialize [DataMember] marked fields from a DataModel class.

That will prevent any unintended behavior to happen knowing that DataContractSerializer does not call the constructor when deserializing.

namespace MyApp.DataModel
{
    //It is not mandatory to specify the DataContract since a default one will be
    //provided on recent version of .Net, however it is a good practice to do so.
    [DataContract(Name = "MyClassDataModel", Namespace = "MyApp.DataModel")]
    public class MyClassDataModel
    {
        [DataMember]
        public bool DataMemberExample{ get; set; }
    }

}

For deserializing and serializing you can now use this class to hold your values.

Upon loading you can create a new data model object and pass it to your class which needs to have its constructor called.

public MyObjectThatNeedToBeConstructed LoadData(){
    // ... 
    // get your reader (Stream) from the file system or wherever it's located
    var deserializer = new DataContractSerializer(typeof(MyClassDataModel));
    var storedModel = (MyClassDataModel)deserializer.ReadObject(reader);

    return new MyObjectThatNeedToBeConstructed(storedModel);
}

Upon saving you can extract the required data from your class that contain the ReadOnly field.

public void SaveData(MyObjectThatNeedToBeConstructed myObject){
    // ... 
    // get your writer (Stream) from memory or wherever it's located
    var serializer = new DataContractSerializer(typeof(MyClassDataModel));
    var dataModel = new MyClassDataModel{ DataMemberExample = myObject.DataMember};
    serializer.WriteObject(writer, dataModel);
}

Of course, you will have to add an overload to the constructor and you might have to tweak the example a bit, but I think you got the picture.

Upvotes: 0

svick
svick

Reputation: 244928

I'm not sure doing this is a good idea, but you can change the value of a readonly field outside the constructor or field initializer by using reflection.

Putting something like:

typeof(MyType).GetField("Field").SetValue(this, value);

in your deserialization callback should work.

Upvotes: 4

Jason Kresowaty
Jason Kresowaty

Reputation: 16510

Yes, using DataContractSerializer you can serialize a readonly field. You can even serialize a non-public readonly field.

using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;

namespace ConsoleApplication30
{
    class Program
    {
        static void Main(string[] args)
        {
            Test a = new Test(1, 2);
            Test b;
            using (var ms = new MemoryStream())
            {
                DataContractSerializer ser = new DataContractSerializer(typeof(Test));
                ser.WriteObject(ms, a);
                ms.Position = 0;
                b = (Test) ser.ReadObject(ms);
            }
            Trace.Assert(a.Data1 == b.Data1);
            Trace.Assert(a.Data2 == b.Data2);
        }
    }

    [DataContract]
    public class Test
    {
        [DataMember]
        public readonly int Data1;

        [DataMember]
        private readonly int _data2;
        public int Data2
        {
            get { return _data2; }   
        }

        public Test(int data1, int data2)
        {
            Data1 = data1;
            _data2 = data2;
        }
    }
}

Upvotes: 3

Related Questions