code_junkie

Enumeration extension methods

Nov 12th, 2011
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. public static void Something(this Enum e)
  2. {
  3. // code here
  4. }
  5.  
  6. public static void EnumExtension(this Enum e)
  7. {
  8. }
  9.  
  10. <Extension()> _
  11. Public Sub EnumExtension(ByVal s As Enum)
  12. End Sub
  13.  
  14. public static class ExtensionMethods
  15. {
  16. public static bool TryParse<T>(this Enum theEnum, string strType,
  17. out T result)
  18. {
  19. string strTypeFixed = strType.Replace(' ', '_');
  20. if (Enum.IsDefined(typeof(T), strTypeFixed))
  21. {
  22. result = (T)Enum.Parse(typeof(T), strTypeFixed, true);
  23. return true;
  24. }
  25. else
  26. {
  27. foreach (string value in Enum.GetNames(typeof(T)))
  28. {
  29. if (value.Equals(strTypeFixed,
  30. StringComparison.OrdinalIgnoreCase))
  31. {
  32. result = (T)Enum.Parse(typeof(T), value);
  33. return true;
  34. }
  35. }
  36. result = default(T);
  37. return false;
  38. }
  39. }
  40. }
  41.  
  42. public enum TestEnum
  43. {
  44. A,
  45. B,
  46. C
  47. }
  48.  
  49. public void TestMethod(string StringOfEnum)
  50. {
  51. TestEnum myEnum;
  52. myEnum.TryParse(StringOfEnum, out myEnum);
  53. }
  54.  
  55. public enum TestEnum
  56. {
  57. A,B,C
  58. }
  59. public void TestMethod(string StringOfEnum)
  60. {
  61. TestEnum myEnum;
  62. myEnum.TryParse(StringOfEnum, out myEnum);
  63. }
  64.  
  65. public enum TestEnum
  66. {
  67. A,B,C
  68. }
  69. public void TestMethod(string StringOfEnum)
  70. {
  71. TestEnum myEnum = default(TestEnum);
  72. myEnum.TryParse(StringOfEnum, out myEnum);
  73. }
Add Comment
Please, Sign In to add comment