Reputation: 8146
I had to write many dozens of lines of code (see here: https://dotnetfiddle.net/RiVx2E) to generate a few lines of sample data.
In this specific case I could manually export the output variable (see the whole code on Fiddler) in this way:
new List {
{ IDMacroTab = 1, IDTab = 1, IDSIot = 2 }
{ IDMacroTab = 1, IDTab = 2, IDSIot 1}
{ IDMacroTab = 1, IDTab = 2, IDSIot = 2}
{ IDMacroTab = 1, IDTab = 2, IDSIot = 3}
{ IDMacroTab = 2, IDTab = 1, IDSIot = 1}
{ IDMacroTab = 2, IDTab = 1, IDSIot = 2 }
{ IDMacroTab = 2, IDTab = 2, IDSIot = 1}
{ IDMacroTab = 2, IDTab = 2, IDSIot = 2}
{ IDMacroTab = 2, IDTab = 2, IDSIot = 3}
{ IDMacroTab = 3, IDTab = 1, IDSIot = 1}
{ IDMacroTab = 3, IDTab = 1, IDSIot = 2}
{ IDMacroTab = 3, IDTab = 2, IDSIot = 1}
{ IDMacroTab = 3, IDTab = 2, IDSIot = 2}
{ IDMacroTab = 3, IDTab = 2, IDSIot = 3}};
Is there any workaround that allows to serialize an object to the c# lines of code required to populate it?
Upvotes: 2
Views: 621
Reputation: 1847
Thrid Solution: ObjectDumper.NET
I might have another solution for you. I was using OmarElabd/ObjectExporter in previous projects with good results but there were problems with some kind of types (e.g. serializations of DateTime didn't work properly at the time). Performance was key too: Some generated objects had a size of 50k lines of code (yeh, don't mention this is too big for a single test data class, I know, but...).
After all, I started writing my own ObjectDumper which you can find published as a NuGet package here. The source code is hosted on github, so feel free to contribute. https://www.nuget.org/packages/ObjectDumper.NET/
The idea of ObjectDumper.NET is that you can dump basically any C# object back to C# initializer code. Compared to ObjectExporter (which is a Visual Studio plug-in), ObjectDumper is installed as NuGet Package. This allows ObjectDumper to be used at runtime - not only at the time of code creation.
Example Usage:
[Fact]
public void SerializeObjectsToInitializerCode()
{
// Create C# object
var testObjects = new List<TestObject>
{
new TestObject {IDMacroTab = 1, IDTab = 1, IDSIot = 2},
new TestObject {IDMacroTab = 1, IDTab = 2, IDSIot = 1},
new TestObject {IDMacroTab = 1, IDTab = 2, IDSIot = 2}
};
// Pass it to ObjectDumper, choose DumpStyle.CSharp to generate C# initializer code
var dump = ObjectDumper.Dump(testObjects, DumpStyle.CSharp);
// Print to console, write to file, etc...
_testOutputHelper.WriteLine(dump);
}
Upvotes: 2
Reputation: 8146
I've found this question which can be pretty useful but just for some kind of object (i.e. lists)
And also this plugin ObjectExporter (last update 2017; checked at 2018)
https://marketplace.visualstudio.com/items?itemName=OmarElabd.ObjectExporter
Upvotes: -1