forme forme
forme forme

Reputation: 63

How to convert a String line to class

I converted class objet to String line

As in the following example

    public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public string Address { get; set; }
        public override string ToString()
        {
            return $"{ID}|{Name}|{Surname}|{Address}";
        }
    }

        Person person = new Person();
        person.Name = "test1";
        person.Surname = "test2";
        person.Address = "test3";

        var _String = person.ToString();
        Console.WriteLine(_String);

This is the output

0|test1|test2|test3

I want to convert the line (0|test1|test2|test3) to class objet

What is the best way to do this to dotnet standard 2.0

Upvotes: 2

Views: 206

Answers (1)

Xerillio
Xerillio

Reputation: 5261

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.

Upvotes: 2

Related Questions