Skip to content

Instantly share code, notes, and snippets.

@pinalbhatt
Last active August 29, 2015 14:04
Show Gist options
  • Save pinalbhatt/af652fbca4e543bc3c23 to your computer and use it in GitHub Desktop.
Save pinalbhatt/af652fbca4e543bc3c23 to your computer and use it in GitHub Desktop.
/*
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