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 1,706 other followers

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;
        try
        {
            var ttype = typeof(T);
            if (ttype.IsEnum)
            {
                T n = default(T);
                if (Enum.TryParse(text, true, out n))
                    return n;
            }
            else
                o = Convert.ChangeType(text, ttype);
        }
        catch { }

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

        return new Nullable((T)o);
    }

–jeroen

One Response to “c# – Generics and nullable type – Stack Overflow”

  1. […] problem was that I felt my code was convoluted, and should be denser, especially avoiding Convert.ChangeType. My code was already much simpler than casting tuples to a […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: