O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.3. Converting a String Representation of an Object into an Actual Object

Problem

You need a way of accepting a string containing a textual representation of an object and converting it to an object usable by your application. For example, if you were provided with the string representation of a line (x1, y1)(x2, y2), you would want to convert it into a Line structure.

Solution

Implement a Parse method on your Line structure:

using System;
using System.Text;
using System.Text.RegularExpressions;

public struct Line
{
    public Line(int startX, int startY, int endX, int endY)
    {
        x1 = startX;
        x2 = endX;
        y1 = startY;
        y2 = endY;
    }

    public int x1;
    public int y1;
    public int x2;
    public int y2;

    public static Line Parse(string stringLine)
    {
        if (stringLine == null)
        {
            throw (new ArgumentNullException("stringLine", 
                       "A null cannot be passed into the Parse method."));
        }

        // Take this string (x1,y1)(x2,y2) and convert it to a Line object
        int X1 = 0;
        int Y1 = 0;
        int X2 = 0;
        int Y2 = 0;

        MatchCollection MC = Regex.Matches(stringLine, 
                @"\s*\(\s*(?<x1>\d+)\s*\,\s*(?<y1>\d+)\s*\)\s*
                     \(\s*(?<x2>\d+)\s*\,\s*(?<y2>\d+)\s*\)" );

        if (MC.Count == 1)
        {
            Match M = MC[0];
            X1 = int.Parse(M.Groups["x1"].Value);
            Y1 = int.Parse(M.Groups["y1"].Value);
            X2 = int.Parse(M.Groups["x2"].Value);
            Y2 = int.Parse(M.Groups["y2"].Value);
        }
        else
        {
            throw (new ArgumentException(
              "The value " + stringLine + " is not a well formed Line value."));
        }

        return (new Line(X1, Y1, X2, Y2));
    }
}

Discussion

The Parse method is used to reconstruct ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required