How can I serialize an object to C# object initializer code?

There is an interesting Visual Studio extension that addresses this; the Object Exporter. It allows serialization of an in-memory object into C# Object initialization code, JSON and XML. I haven't tried it yet but looks intriguing; will update after trying it out.


If your model is simple, you could use reflection and a string builder to output C# directly. I've done this to populate unit test data exactly as you discussed.

The code sample below was written in a few minutes and generated an object initializer that needed some hand tweaking. A more robust / less buggy function could be written if you plan on doing this a lot.

The second function is recursive, iterating over any Lists within the object, and generating code for those as well.

Disclaimer: This worked for my simple model with basic data types. It generated code that needed cleanup but allowed me to move on quickly. It is only here to serve as an example of how this could be done. Hopefully, it inspires someone to write their own.

In my case, I had an instance of this large dataset (results) that was loaded from the database. In order to remove the database dependency from my unit test, I handed the object to this function which spits out the code that allowed me to mock the object in my test class.

    private void WriteInstanciationCodeFromObject(IList results)
    {

        //declare the object that will eventually house C# initialization code for this class
        var testMockObject = new System.Text.StringBuilder();

        //start building code for this object
        ConstructAndFillProperties(testMockObject, results);

        var codeOutput = testMockObject.ToString();
    }


    private void ConstructAndFillProperties(StringBuilder testMockObject, IList results)
    {

        testMockObject.AppendLine("var testMock = new " + results.GetType().ToString() + "();");

        foreach (object obj in results)
        {

            //if this object is a list, write code for its contents

            if (obj.GetType().GetInterfaces().Contains(typeof(IList)))
            {
                ConstructAndFillProperties(testMockObject, (IList)obj);
            }

            testMockObject.AppendLine("testMock.Add(new " + obj.GetType().Name + "() {");

            foreach (var property in obj.GetType().GetProperties())
            {

               //if this property is a list, write code for its contents
                if (property.PropertyType.GetInterfaces().Contains(typeof(IList)))
                {
                    ConstructAndFillProperties(testMockObject, (IList)property.GetValue(obj, null));
                }

                testMockObject.AppendLine(property.Name + " = (" + property.PropertyType + ")\"" + property.GetValue(obj, null) + "\",");
            }

            testMockObject.AppendLine("});");
        }
    }

It's possible the object will have a TypeConverter that supports conversion to InstanceDescriptor, which is what the WinForms designer uses when emitting C# code to generate an object. If it can't convert to an InstanceDescriptor, it will attempt to use a parameterless constructor and simply set public properties. The InstanceDescriptor mechanism is handy, since it allows you to specify various construction options such as constructors with parameters or even static factory method calls.

I have some utility code I've written that emits loading of an in-memory object using IL, which basically follows the above pattern (use InstanceDescriptor if possible and, if not, simply write public properties.) Note that this will only produce an equivalent object if the InstanceDescriptor is properly implemented or setting public properties is sufficient to restore object state. If you're emitting IL, you can also cheat and read/write field values directly (this is what the DataContractSerializer supports), but there are a lot of nasty corner cases to consider.