Click here to Skip to main content
15,921,113 members
Articles / Programming Languages / C# 4.0

C# Universal String Parsing Utility

Rate me:
Please Sign up or sign in to vote.
3.21/5 (8 votes)
10 Aug 2012CPOL 31.6K   22   11
A simple utility to help convert strings into other types

The Problem

Parsing strings into other objects using tryParse() is a pain, and results in ugly code. I was sick and tired of seeing this kind of thing all over my projects:

C#
var someStringThatShouldBeAnInt = "10";
int i = 0;
if(int.TryParse(someStringThatShouldBeAnInt, out i))
{
    //Continue on with things
}else
{
    //Complain about it
} 

The Desired Solution 

Abstract this ugliness and replace it with something like this: 

C#
var someStringThatShouldBeAnInt = "10";
var i = someStringThatShouldBeAnInt.Parse<int>();

The How

Seems like if I could dynamically call the tryParse() using Reflection I could write this once for every type that has the tryParse() available to it.

C#
public static T Parse<T>(this string thingToParse)
{
    var retType = typeof(T);
    var tParse = retType.GetMethod("TryParse",
                                   BindingFlags.Public | BindingFlags.Static, null,
                                   new[] { typeof(string), retType.MakeByRefType() }, null);

    if (tParse != null)
    {
        var parameters = new object[] { thingToParse, null };
        var success = (bool)tParse.Invoke(null, parameters);
        if (success)
        {
            return (T)parameters[1];
        }
    }

    return default(T);
}

What If the type you are converting to doesn't implement tryParse()?

C#
var csv = "1,2,3,4,5,6,7";
var list = csv.Parse<List<string>>();

Yea that’s not going to work. So let's give you the option to pass in your own converter.

C#
public static T Parse<T>(this string thingToParse, Func<string, T> parser)
{
    return parser.Invoke(thingToParse);
}

Wow that’s even cleaner. Now we can do the following:

C#
var csv = "1,2,3,4,5,6,7";
var list = csv.Parse<List<string>>(x => x.Split(',').ToList());

Yea that’s clean.

If you find this useful or see ways to improve please feel free to comment.

You can also find some other great topics over at my blog at: http://www.sympletech.com.

This utility can be found with many others here: https://github.com/sympletech/SympleLib.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Sympletech
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Clifford Nelson6-Aug-12 7:49
Clifford Nelson6-Aug-12 7:49 
QuestionSorry, no vote from me Pin
Thorsten Bruning4-Aug-12 7:05
Thorsten Bruning4-Aug-12 7:05 
Because it is not an article - but this was already said.
It would really be a good tip! I would have spend my 5 then Thumbs Up | :thumbsup:

But if you are interested in more conversions, you might want to look at the Universal Type Converter[^]. It does a lot of stuff you are looking for. And I was surprised how much different conversion-methods are available - so I think you don't have to figure them out on your own, again Wink | ;)

However - it's nice that you spent your time on sharing your knowledge, thanks!
10 Home
20 Sweet
30 goto 10

QuestionThanks All for the feedback. Pin
Sympletech3-Aug-12 18:31
Sympletech3-Aug-12 18:31 
GeneralMy vote of 3 Pin
BillWoodruff3-Aug-12 12:09
professionalBillWoodruff3-Aug-12 12:09 
Questionmy vote of #3, and one "editorial suggestion" Pin
BillWoodruff3-Aug-12 12:08
professionalBillWoodruff3-Aug-12 12:08 
GeneralMy vote of 4 Pin
Ian Shlasko3-Aug-12 10:54
Ian Shlasko3-Aug-12 10:54 
GeneralMy vote of 4 Pin
Christian Amado3-Aug-12 9:42
professionalChristian Amado3-Aug-12 9:42 
AnswerNot enough content for article Pin
Clifford Nelson3-Aug-12 8:34
Clifford Nelson3-Aug-12 8:34 
AnswerRe: Not enough content for article Pin
Clifford Nelson6-Aug-12 7:51
Clifford Nelson6-Aug-12 7:51 
GeneralRe: Not enough content for article Pin
BillW3310-Aug-12 10:17
professionalBillW3310-Aug-12 10:17 
GeneralRe: Not enough content for article Pin
Sympletech10-Aug-12 10:32
Sympletech10-Aug-12 10:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.