Last active
August 29, 2015 14:04
-
-
Save pinalbhatt/af652fbca4e543bc3c23 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
C# Generic String Parser Extension Method | |
Code Snippet By: Pinal Bhatt [www.PBDesk.com] | |
http://blogs.pbdesk.com/c-generic-string-parser-extension-method/ | |
Working Example at http://ideone.com/ZP5xo | |
Usage: | |
string s = "32"; | |
int i = s.As<int>(); | |
*/ | |
using System.ComponentModel; | |
using System; | |
public static class StringExtensions | |
{ | |
public static T As<T>(this string strValue, T defaultValue) | |
{ | |
T output = defaultValue; | |
if (output == null) | |
{ | |
output = default(T); | |
} | |
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); | |
if (converter != null) | |
{ | |
try | |
{ | |
output = (T)converter.ConvertFromString(strValue); | |
} | |
catch (Exception ex) | |
{ | |
throw ex; | |
} | |
} | |
return output; | |
} | |
public static T As<T>(this string strValue) | |
{ | |
return strValue.As<T>(default(T)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment