Pangamma

C# ToNullableStringExtension

Apr 23rd, 2016 (edited)
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.45 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5.  
  6. namespace YourNameSpaceHere
  7. {
  8.     public static class ToNullableStringExtension
  9.     {
  10.         /// <summary>
  11.         /// <para>More convenient than using T.TryParse(string, out T).
  12.         /// Works with primitive types, structs, and enums.
  13.         /// Tries to parse the string to an instance of the type specified.
  14.         /// If the input cannot be parsed, null will be returned.
  15.         /// </para>
  16.         /// <para>
  17.         /// If the value of the caller is null, null will be returned.
  18.         /// So if you have "string s = null;" and then you try "s.ToNullable...",
  19.         /// null will be returned. No null exception will be thrown.
  20.         /// </para>
  21.         /// <author>Contributed by Taylor Love (Pangamma)</author>
  22.         /// </summary>
  23.         /// <typeparam name="T"></typeparam>
  24.         /// <param name="p_self"></param>
  25.         /// <returns></returns>
  26.         public static T? ToNullable<T>(this string p_self) where T : struct
  27.         {
  28.             if (!string.IsNullOrEmpty(p_self))
  29.             {
  30.                 var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
  31.                 if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self);
  32.                 if (typeof(T).IsEnum) { T t; if (Enum.TryParse<T>(p_self, out t)) return t;}
  33.             }
  34.  
  35.             return null;
  36.         }
  37.     }
  38. }
Add Comment
Please, Sign In to add comment