The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,975 other subscribers

Archive for June 14th, 2011

c# – Generics and nullable type – Stack Overflow

Posted by jpluimers on 2011/06/14

A while ago, I needed some generic way of parsing data that could result instancef of both regular ordinal and nullable ordinal types.

Luckily there was a nice question about this on StackOverflow, of which I liked this answer (source code below) much more than the accepted answer: concise, elegant, period.

    public static T? Parse(this string text) where T: struct
        object o = null;
            var ttype = typeof(T);
            if (ttype.IsEnum)
                T n = default(T);
                if (Enum.TryParse(text, true, out n))
                    return n;
                o = Convert.ChangeType(text, ttype);
        catch { }

        if (o == null)
            return new Nullable();

        return new Nullable((T)o);


Posted in .NET, C#, C# 2.0, C# 3.0, C# 4.0, Development, Software Development | 1 Comment »

%d bloggers like this: