tags:

views:

120

answers:

5

I have a string value that needs to be converted into my user defined custom type. how to do this, please help me.

public class ItemMaster
{
    public static ItemMaster loadFromReader(string oReader)
    {
        return oReader;//here i am unable to convert into ItemMaster type
    }
}
+2  A: 

Create a Parse method on your User Defined Custom type:

public class MyCustomType
{
    public int A { get; private set; }
    public int B { get; private set; }

    public static MyCustomType Parse(string s)
    {
        // Manipulate s and construct a new instance of MyCustomType
        var vals = s.Split(new char[] { '|' })
            .Select(i => int.Parse(i))
            .ToArray();

        if(vals.Length != 2)
            throw new FormatException("Invalid format.");

        return new MyCustomType { A = vals[0], B = vals[1] };            
    }
}

Granted, the example provided is extremely simple but it at least will get you started.

Justin Niessner
can you give me example?
Pradeep
A: 

For the actual conversion, we would need to see the class structure for. The skeleton for this would look as follows however:

class MyType
{
    // Implementation ...

    public MyType ConvertFromString(string value)
    {
        // Convert this from the string into your type
    }
}
Kyle Rozendo
A: 

Convert.ChangeType() method may help you.

string sAge = "23";
int iAge = (int)Convert.ChangeType(sAge, typeof(int));
string sDate = "01.01.2010";
DateTime dDate = (DateTime)Convert.ChangeType(sDate, typeof(DateTime));
Musa Hafalır
No way of knowing with this, as it's a user defined type.
Kyle Rozendo
+2  A: 

Depending on your type there are two ways that you could do it.

The first is adding a constructor to your type that takes a String parameter.

public YourCustomType(string data) {
    // use data to populate the fields of your object
}

The second is adding a static Parse method.

public static YourCustomType Parse(string input) {
    // parse the string into the parameters you need
    return new YourCustomType(some, parameters);
}
jjnguy
Good answer, Just a note on the second example - the status quo is to name this method `Parse`.
Jamiec
@Jamiec, yeah, I know that, but I think the `FromString` name is so much more descriptive.
jjnguy
@Jamie, I changed the name of the method.
jjnguy
A: 

First you need to define a format that your type will follow when being converted to a string. A simple example is a social security number. You can easily describe it as a regular expression.

\d{3}-\d{2}-\d{4}

After that you simple need to reverse the process. The convention is to define a Parse method and a TryParse method for your type. The difference being that TryParse will not throw an exception.

public static SSN Parse(string input)
public static bool TryParse(string input, out SSN result)

Now the process you follow to actually parse the input string can be as complex or as simple as you wish. Typically you would tokenize the input string and perform syntactic validation. (EX: Can a dash go here?)

number
dash
number
dash
number

It really depends on how much work you want to put into it. Here is a basic example of how you might tokenize a string.

private static IEnumerable<Token> Tokenize(string input)
{ 
    var startIndex = 0;
    var endIndex = 0;
    while (endIndex < input.Length)
    {            
        if (char.IsDigit(input[endIndex]))
        {
            while (char.IsDigit(input[++endIndex]));
            var value = input.SubString(startIndex, endIndex - startIndex);
            yield return new Token(value, TokenType.Number);
        }
        else if (input[endIndex] == '-')
        {
            yield return new Token("-", TokenType.Dash);
        }
        else
        {
            yield return new Token(input[endIndex].ToString(), TokenType.Error);
        }
        startIndex = ++endIndex;
    }
}
ChaosPandion