Accepted answer

If you check what _String.Split('|') returns, you'll see that it gives a string[]. This string-array contains each part of _String on either sides of the | characters, so:

var person = new Person()
    ID = 1,
    Name = "James",
    Surname = "Smith",
    Address = "James's Road 123"

var _String = person.ToString(); // "1|James|Smith|James's Road 123"

var stringSplit = _String.Split("|"); // ["1", "James", "Smith", "James's Road 123"]

Now, you have all 4 parts of the person you want to create, so now you can recreate the person:

var recreatedPerson = new Person()
    ID = stringSplit[0],
    Name = stringSplit[1],
    Surname = stringSplit[2],
    Address = stringSplit[3]

You might notice the first line in the person will fail (ID = stringSplit[0]) because stringSplit[0] is a string, but ID expects an int. So to convert a string into an int we need to parse it:

ID = int.Parse(stringSplit[0])

Remember, if you do not give the original person an ID the string-array will not have an ID either, in which case the above parsing will fail. But I'll let you think about how you could handle that.

EDIT: as stated in the comments to your question, if this is not just a little exercise in learning C#, and if you are really looking for a proper way of turning an object into a string and vice versa, you should look into serializing your objects using JSON, XML or similar.

Related Articles