Last active
August 29, 2015 14:10
-
-
Save nauzilus/e9defd865ca3bac53f36 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
using System; | |
using System.ComponentModel; | |
public static class Conversion { | |
public static T TryAs<T>(this string x, T otherwise = default(T)) | |
{ | |
var converter = TypeDescriptor.GetConverter(typeof(T)); | |
if (converter != null && x != null && converter.CanConvertFrom(x.GetType())) | |
{ | |
try { return (T)converter.ConvertFrom(x); } | |
catch{} | |
} | |
return otherwise; | |
} | |
} |
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
using System; | |
using Conversion; | |
public class Program | |
{ | |
public enum FooBar { Unknown, Foo, Bar } | |
public static void Main() | |
{ | |
Console.WriteLine("42".TryAs<int>() == 42); | |
Console.WriteLine("42x".TryAs<int>() == default(int)); | |
Console.WriteLine("42x".TryAs<int>(16) == 16); | |
Console.WriteLine("42x".TryAs<int?>() == null); | |
Console.WriteLine("42x".TryAs<int?>(16) == 16); | |
Console.WriteLine("foo".TryAs<FooBar> () == FooBar.Foo); | |
Console.WriteLine("xfoo".TryAs<FooBar> () == default(FooBar)); | |
Console.WriteLine("xfoo".TryAs<FooBar?>() == null); | |
string nullThing = null; | |
Console.WriteLine(nullThing.TryAs<int?>() == null); | |
Console.WriteLine(nullThing.TryAs<int>(42) == 42); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment