Quantcast
Channel: Serialize an object to string - Stack Overflow
Viewing all articles
Browse latest Browse all 12

Answer by satibel for Serialize an object to string

$
0
0

In some rare cases you might want to implement your own String serialization.

But that probably is a bad idea unless you know what you are doing. (e.g. serializing for I/O with a batch file)

Something like that would do the trick (and it would be easy to edit by hand/batch), but be careful that some more checks should be done, like that name doesn't contain a newline.

public string name {get;set;}public int age {get;set;}Person(string serializedPerson) {    string[] tmpArray = serializedPerson.Split('\n');    if(tmpArray.Length>2 && tmpArray[0].Equals("#")){        this.name=tmpArray[1];        this.age=int.TryParse(tmpArray[2]);    }else{        throw new ArgumentException("Not a valid serialization of a person");    }}public string SerializeToString(){    return "#\n"+           name +"\n"+           age;}

Viewing all articles
Browse latest Browse all 12

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>