Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to custom object with Convert

Tags:

c#

I found following statement in Programming in C# book:

IFormattable provides the functionality to format the value of an object into a string representation. It is also used by the Convert class to do the opposite.

I have class:

class a : IFormattable
{
    private string aa = "123";
    private int bb = 5;

    public string ToString(string format, IFormatProvider formatProvider)
    {
        return $"aa={aa} bb={bb}" ;
    }
}

But how to convert string by using Convert into object of a?

UPD: I know idea of parsing. But my question is how to use Convert class to create new object from string.

like image 600
vico Avatar asked Oct 17 '22 04:10

vico


1 Answers

You could provide an explicit conversion operator:

public class A : IFormattable
{
    public string Aa { get; } = "123";
    public int Bb { get; } = 5;

    public A(){ }

    public A(string aa, int bb)
    {
        this.Aa = aa;
        this.Bb = bb;
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
        return $"aa={Aa} bb={Bb}";
    }

    public static explicit operator A(string strA)  
    {
        if (strA == null) return null;
        if (!strA.Contains("aa=") || !strA.Contains(" bb=")) return null;
        string[] parts = strA.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
        if (parts.Length != 2 || !parts[0].StartsWith("aa=") || !parts[1].StartsWith("bb=")) return null;

        string aa = parts[0].Substring(3);
        string bb = parts[1].Substring(3);
        int bbInt;
        if (!int.TryParse(bb, out bbInt)) return null;
        A a = new A(aa, bbInt);
        return a;
    }
}

Sample:

A a = new A("987", 4711);
string toString = a.ToString(null, null);
a = (A) toString;
like image 67
Tim Schmelter Avatar answered Nov 01 '22 09:11

Tim Schmelter