C# 9 records have { propertyName=value } output from ToString(), how to get from that, back to the record type?

Viewed 138

Given

        public record SimpleRec(string PropertyName);

        [TestMethod]
        public void Test()
        {
            var simpleRecord = new SimpleRec("property");
            var recordString = simpleRecord.ToString();

            Console.WriteLine(recordString);
        }

Output:

SimpleRec { PropertyName = property }

Is there an equally simple way to instantiate a SimpleRec from recordString?

I was hoping we wouldn't have to mess with XML or JSON serializers.


What puzzles me is that they chose the above string format for the conversion to string in the first place. If it had output Xml, JSON or even YAML, reversing the process would be fairly simple.

I think I want a generic fix for this. Maybe a conversion extension method, but then I need to figure out how to select on record types only. That or just use JSON serialize/deserialize and ignore the default baked-in ToString().


I tried this:

var converted = (SimpleRec)Convert.ChangeType(recordString, typeof(SimpleRec));

But threw an InvalidCastException.

1 Answers

The ToString used here is not meant for programmatic use in this kind of parsing way - it is meant to be useful for debugging, and nothing more. If you need something deterministic: write your own ToString, or use a serializer of your choice.

Related