Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to auto-generate object initialization code from a runtime object with values?

Maybe a long shot, but if this existed it would save me some time.

To explain in more detail. Let's say I have a long XML file and a mapped class. I want to test stuff and change values around before I run a test. I could re-construct the whole XML structure by writing C# code for initializing that mapped class, but what I want to know is - Do I absolutely have to ?

So basically I want to parse a big XML File into an object at runtime and then I generate the initialization code as a string I could just paste somewhere. Let's say the input is :

<MyObject>
    <Prop1>a</Prop1>
    <Prop2>b</Prop2>
    <Prop2>c</Prop2>
</MyObject>

And I would like a string like this for example:

"new MyObject() 
{
    Prop1 = "a",
    Prop2 = "b",
    Prop3 = "c"
}"
like image 811
valorl Avatar asked Nov 21 '25 09:11

valorl


1 Answers

I was having the same issue since all my test data was stored as XML. The mentioned Visual Studio Extension (OmarElabd/ObjectExporter) was a good idea, but I needed to generate C# code from in-memory objects at runtime, during unit test execution.

This is what evolved from the original problem: https://www.nuget.org/packages/ObjectDumper.NET/

ObjectDumper.Dump(obj, DumpStyle.CSharp); returns C# initializer code from a variable. Please let me know if you find issues, you might want to report them on github.

like image 90
thomasgalliker Avatar answered Nov 24 '25 00:11

thomasgalliker