Guest User

Untitled

a guest
Jul 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. /// <summary>
  2. /// Use for easy convertion from string to matching enum
  3. /// </summary>
  4. /// <typeparam name="T">Type beeing an Enum </typeparam>
  5. /// <param name="value">String representing the Enum value</param>
  6. /// <returns></returns>
  7. public static T ParseAsEnum<T>(this String value)
  8. {
  9. if (string.IsNullOrEmpty(value))
  10. {
  11. throw new ArgumentNullException("value", "Kann keinen leeren String ");
  12. }
  13.  
  14. Type enumType = typeof(T);
  15. if (!enumType.IsEnum)
  16. {
  17. throw new InvalidOperationException("T must be an enum");
  18. }
  19.  
  20. if(Enum.IsDefined(enumType, value))
  21. {
  22. return (T)Enum.Parse(enumType, value);
  23. }else
  24. {
  25. throw new InvalidEnumArgumentException("Kein Enumwert in " + enumType.ToString() + " namens " + value + " bekannt");
  26. }
  27.  
  28. }
Add Comment
Please, Sign In to add comment