-2

Suppose I have a simple class like that:

public class Person {
    public string name;
    public int age;
    public Gender gender; //enum type

    //constructor
}

Is there a built-in way to parse an object of this class to a string and then, back to Person?

I probably will implement a ToString() myself but I'd like to know if there is something already made for this.

The string doesn't need to be comprehensible, as long as it is invertible.


Example

Person p = new Person("Bob", 12, Gender.Male);
string s = Stringify(p);   //s = "Bob#12#Male"
Person c = Personify(s);   //c is just like Bob
Daniel
  • 7,357
  • 7
  • 32
  • 84
  • 3
    you can serialize an object into json string. https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to – Nonik Aug 05 '20 at 03:26
  • 1
    You can use xml as well... – Trevor Aug 05 '20 at 03:28
  • [This](https://stackoverflow.com/questions/2434534/serialize-an-object-to-string) has different examples that work along with many others here on SO, choose one to fit your requirements. – Trevor Aug 05 '20 at 03:46

1 Answers1

4

You can use many sorts of serialization to achieve this, one simple approach would be to use Json.net

Example

var funkyString = JsonConvert.SerializeObject(person);
var person = JsonConvert.DeserializeObject<person>(funkyString);

Note : If in .NET Core 3.x, you no longer need Json.net. There is now a Json serializer in the framework. – insane_developer

If you want more control over what the string looks like, one approach would be to override ToString() in your class, and write a custom decoder to unencode your data and set your properties (this would be easy to get wrong for more complex types).

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • 1
    If in .NET Core 3.x, you no longer need Json.net. There is now a [Json serializer](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer?view=netcore-3.1) in the framework. – insane_developer Aug 05 '20 at 04:01