Click here to Skip to main content
13,860,694 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


51 bookmarked
Posted 13 Nov 2010
Licenced CPOL

String conversions made easy

, 4 Dec 2010
Rate this:
Please Sign up or sign in to vote.
Convert strings to their strong typed counterpart with String.ConvertTo().


Every programmer has them lying around, you know what I'm talking about, those little utility functions that help with string conversions. Especially in website development, where everything is treated as plain text, I can't go without some easy functions to help me with the parsing of DateTimes, Booleans, Integers, and GUIDs, amongst others.

When I recently came across an article about TypeConverters, I immediately saw this opportunity to come up with a single Extension Method (with some overloads) that plugs right into the String class.

bool b      = "true".ConvertTo<bool>();
DateTime d1 = " 01:23:45 ".ConvertTo<DateTime>();
Point p     = "100,25".ConvertTo<Point>();

//convert, but use specific culture. 
//in this case the comma is used as a decimal seperator
Double d    = "1.234,567".ConvertTo<double>("NL")

//provide a default value, if conversion fails
Guid g      = "i'm not a guid".ConvertTo<Guid>(Guid.Empty);


Although the Microsoft .NET Framework has plenty of conversion methods, for some reason, I always had difficulty when it came to 'proper' string handling. Localized date times that weren't understood, numbers that could only be parsed if I removed the separators, etc., and yet more methods to work with Enumerator values.

When I started experimenting with the TypeConverter, it seemed just too good to be true. But as always, I soon came back to earth when "it" wasn't too impressed with my localized numbers, e.g., -1.234,56. Anyway, I've managed to resolve this in what seems like a nice clean Extension Method that integrates into the String class.

Using the code

All the hard work is done by TypeConverters, which according to the MSDN documentation, provides a unified way of converting types of values to other types, as well as for accessing standard values and subproperties. I was particularly interested in the conversion from string to its strong typed counterpart, which can easily be achieved as explained by Scott.

TypeConverter converter =  TypeDescriptor.GetConverter(typeof(double))
converter.ConvertFromString(null, null, text);

All that was left to do was wrapping this inside a generic function and adding two sets of overloads, which basically allow you to interpret the string and convert it to its defined type. But, if the format of the String can not be understood by the TypeConverter, it will raise an Exception.

//this will through an exception
//because the text can not be converted to the specified type

int x = "abcd".ConvertTo<int>();

//even this one will fail due to the localization that is set 
//to dutch where comma's are used as decimal separators

int y = "1,234.56".ConvertTo<int>("NL");

The other set of methods allows you to specify a default value which will be used if the TypeConverter fails, in which case the Exception will be suppressed.

//use default value if TypeConverter will fail
DateTime a = "i'm not a date".ConvertTo<DateTime>(DateTime.Today);

//or with localization support
Double  b = "1a".ConvertTo<Double>(CultureInfo.InstalledUICulture, -1);

Do take a look at the ugly part which resolves the "Numbers issue", by by-passing the BaseNumberConverter. It's not elegant or pretty, but it is contained and does the job. You might even want to swap out other TypeConverters, for example, the BooleanConverter in order to be able to handle strings like Yes, No, On, Off, etc.


  • 04-Dec-2010: Updated the source with suggestions from Geswan and Andy. Also, handles unsigned and other exotic numeric types that were missing in the first code base. Last but not least, I've added a custom routine to handle Boolean strings like: Yes, No, On, Off, 1, and 0.


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


About the Author

Elmar de Groot
Software Developer (Senior) WEBelieve
South Africa South Africa
Born and raised in the Netherlands but currently enjoying the South African sunshine with my wife and child. I've been working as a software developer since 1997. Although I'm a self-employed all rounder and get my hands dirty on almost everything I really enjoy building internet applications and providing sound advice to clients that have difficulty keeping up with the fast pace of software development.

You may also be interested in...

Comments and Discussions

GeneralMy vote of 4 Pin
Thorsten Bruning29-Dec-12 1:20
memberThorsten Bruning29-Dec-12 1:20 
GeneralMy vote of 5 Pin
prasad0222-Dec-10 5:42
memberprasad0222-Dec-10 5:42 
GeneralMy vote of 4 Pin
Pranay Rana6-Dec-10 20:34
professionalPranay Rana6-Dec-10 20:34 
GeneralHandling Hex Pin
Dave Hary5-Dec-10 15:04
memberDave Hary5-Dec-10 15:04 
GeneralMy vote of 5 Pin
hussain.attiya5-Dec-10 1:39
memberhussain.attiya5-Dec-10 1:39 
GeneralRe: My vote of 5 Pin
Elmar de Groot5-Dec-10 21:50
memberElmar de Groot5-Dec-10 21:50 
GeneralMy vote of 4 Pin
TweakBird4-Dec-10 11:07
memberTweakBird4-Dec-10 11:07 
GeneralMy vote of 5 Pin
maq_rohit4-Dec-10 3:54
professionalmaq_rohit4-Dec-10 3:54 
GeneralMy vote of 4 Pin
thulzs4-Dec-10 2:22
memberthulzs4-Dec-10 2:22 
GeneralConvert.ChangeType Pin
KevinAG3-Dec-10 14:01
memberKevinAG3-Dec-10 14:01 
GeneralRe: Convert.ChangeType [modified] Pin
Elmar de Groot3-Dec-10 20:35
memberElmar de Groot3-Dec-10 20:35 
GeneralMy vote of 5 Pin
Anurag Gandhi29-Nov-10 9:34
professionalAnurag Gandhi29-Nov-10 9:34 
GeneralMy vote of 5 Pin
Cesar to Dnn29-Nov-10 4:14
professionalCesar to Dnn29-Nov-10 4:14 
GeneralMy vote of 5 Pin
andykernahan25-Nov-10 8:00
memberandykernahan25-Nov-10 8:00 
GeneralMy vote of 5 Pin
John Brett25-Nov-10 3:39
memberJohn Brett25-Nov-10 3:39 
GeneralGood idea Pin
George Swan24-Nov-10 23:22
memberGeorge Swan24-Nov-10 23:22 
GeneralRe: Good idea Pin
Elmar de Groot25-Nov-10 1:12
memberElmar de Groot25-Nov-10 1:12 
GeneralMy vote of 5 Pin
Xmen Real 24-Nov-10 16:10
professional Xmen Real 24-Nov-10 16:10 
GeneralRe: My vote of 5 Pin
Elmar de Groot25-Nov-10 1:28
memberElmar de Groot25-Nov-10 1:28 

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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190214.1 | Last Updated 4 Dec 2010
Article Copyright 2010 by Elmar de Groot
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid