Permalink
Browse files

adding a 'ToEnum' string extension

  • Loading branch information...
1 parent b7aef45 commit 776b7fe4d707a07f851a28b6c6afba57b7132942 @drusellers drusellers committed Jan 12, 2012
Showing with 36 additions and 0 deletions.
  1. +28 −0 src/FubuCore.Testing/StringExtensionsTester.cs
  2. +8 −0 src/FubuCore/StringExtensions.cs
@@ -206,5 +206,33 @@ public void to_hash_is_repeatable()
"something".ToHash().ShouldEqual("something".ToHash());
"else".ToHash().ShouldNotEqual("something".ToHash());
}
+
+
+ [Test]
+ public void to_enum()
+ {
+ var x = "Machine".ToEnum<EnvironmentVariableTarget>();
+ x.ShouldEqual(EnvironmentVariableTarget.Machine);
+ }
+
+ [Test]
+ public void to_enum_should_ignore_case()
+ {
+ var x = "machine".ToEnum<EnvironmentVariableTarget>();
+ x.ShouldEqual(EnvironmentVariableTarget.Machine);
+ }
+
+ [Test]
+ public void to_enum_should_throw_if_not_enum()
+ {
+ Assert.Throws<ArgumentException>(() =>
+ {
+ "a".ToEnum<NotAnEnum>();
+ });
+ }
+ public struct NotAnEnum
+ {
+
+ }
}
}
@@ -269,5 +269,13 @@ public static string ToHash(this string text)
{
return MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(text)).Select(b => b.ToString("x2")).Join("");
}
+
+
+ public static TEnum ToEnum<TEnum>(this string text) where TEnum : struct
+ {
+ var enumType = typeof (TEnum);
+ if(!enumType.IsEnum) throw new ArgumentException("{0} is not an Enum".ToFormat(enumType.Name));
+ return (TEnum) Enum.Parse(enumType, text, true);
+ }
}
}

0 comments on commit 776b7fe

Please sign in to comment.