1

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
    }
}
8
  • 4
    Could you post an example of what you're trying to do? Commented Aug 31, 2010 at 14:39
  • 9
    It is possible to be more vague, you know. Commented Aug 31, 2010 at 14:40
  • 1
    This is too vague to answer as is. The answer will depend on your user-defined custom type and the format and content of the string value. If you want useful answers, you'll probably have to give some more details in your question. Commented Aug 31, 2010 at 14:40
  • 4
    What type is the user defined custom type? An image? A boolean? Are you possibly converting a string into a kitten? Commented Aug 31, 2010 at 14:41
  • 1
    @Blair: Not too vague if you are just after rep ;) Assumptions can lead you a long way, often down the wrong path but you'll have an upvote or two before it becomes apparent. Commented Aug 31, 2010 at 14:47

5 Answers 5

5

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Good answer, Just a note on the second example - the status quo is to name this method Parse.
@Jamiec, yeah, I know that, but I think the FromString name is so much more descriptive.
@Jamie, I changed the name of the method.
2

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));

1 Comment

No way of knowing with this, as it's a user defined type.
2

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.

Comments

1

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;
    }
}

Comments

0

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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.