Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive


Modified: 2009/03/02 10:10 by arjan - Categorized as: ASP.NET, Csharp, Extension Method


Generic string parse extension method

This extension method parses a string into any type. The overload returns a default value in case the parser fails, in that case you dont need to spcity the type.

using System;
using System.ComponentModel;

namespace System { public static class StringParser { public static T Parse<T>(this string value) { if (string.IsNullOrEmpty(value)) { return default(T); } TypeConverter tc = TypeDescriptor.GetConverter(typeof(T)); return (T)tc.ConvertFrom(value); }

public static T Parse<T>(this string value, T failValue) { if (string.IsNullOrEmpty(value)) { return default(T); } try { TypeConverter tc = TypeDescriptor.GetConverter(typeof(T)); return (T)tc.ConvertFrom(value); } catch (Exception) { return failValue; } }

public static void ParseEXAMPLE() { int a = "123".Parse<int>(); float b = "123,456".Parse<float>(); Guid c = "778b8d78-348a-41da-ab46-13a69a51d3d4".Parse<Guid>();

int a1 = "no int".Parse(-1); float b1 = "not a float".Parse(-2); Guid c1 = "no guid !".Parse(Guid.NewGuid()); } } }

 © Evident Interactive BV