1

Roslyn scripting allows to evaluate a C# script containing just an object creation expression, effectively allowing to deserialize objects from scripts:

var script = "new Point { X = 1, Y = 2 }";
var point = await CSharpScript.EvaluateAsync<T>(script);

Is there a library that allows to do the reverse serialization?

script = ???.Serialize(point);
Andriy Svyryd
  • 2,021
  • 1
  • 19
  • 26
  • 1
    That's not serialization, it's scripting, Roslyn interprets the string as code. – Gusman Oct 27 '16 at 22:07
  • The idea is to use this in a way similar to JSON – Andriy Svyryd Oct 27 '16 at 22:08
  • 1
    If you want just serialization, use serialization, evaluating code as script is by far slower than just serializing. – Gusman Oct 27 '16 at 22:11
  • I want to have the strong typing and expressiveness of C#, performance is not a big concern – Andriy Svyryd Oct 27 '16 at 22:12
  • 1
    Using JSON.net you can explicitly tell the serializer/deserializer to include full class names so it will be strongly typed. Anyway, Roslyn can't do any of this, the most approximate you can do is to use ILSpy: http://stackoverflow.com/questions/29567489/can-roslyn-generate-source-code-from-an-object-instance But that will not give you the result you expect, it will return the declarative C# code, not the code from a class with it's properties already set. – Gusman Oct 27 '16 at 22:15
  • the "???" part is what would be ugly, it would mean you could call `.Serialize(point);` from litereally anywhere. Also, how to tell where this serialization should start? I don't think thats possible... – nozzleman Oct 28 '16 at 05:33
  • @nozzleman Why it would be ugly? Converting an instance/a struct into a string that can be deserialized later is the common job that XML/JSON serializers do every day and noone will call them ugly. So it is possible but I would not recommend it :o) – Sir Rufo Oct 28 '16 at 07:14
  • @SirRufo when it comes to objects, of course, you are right, the SCriptEvaluation is more powerfull than that. What i was referring to was to "serialize" parts of of a method for example. How to tell from where to where (which statements) the serialization should happen? – nozzleman Oct 28 '16 at 07:36
  • @nozzleman He never mentioned to serialize a method call ;o) – Sir Rufo Oct 28 '16 at 09:06
  • @SirRufo thats right, but `new Point { X = 1, Y = 2 }` is more of a statement but an `object` ;) – nozzleman Oct 28 '16 at 11:39

1 Answers1

1

Since there doesn't appear to be an existing library that can accomplish this I wrote one that should handle the simple cases: https://github.com/AndriySvyryd/CSharpScriptSerializer

var input = new Point {X = 1, Y = 1};
var script = CSScriptSerializer.Serialize(input);
var output = CSScriptSerializer.Deserialize<Point>(script);
m0sa
  • 10,712
  • 4
  • 44
  • 91
Andriy Svyryd
  • 2,021
  • 1
  • 19
  • 26