Reputation: 11430
Is it possible to do something like this:
public static T ToEnum<T>(this string s, Type T)
{
return (T)Enum.Parse(typeof(T), s);
}
Or in some other way, that is, using the argument T as the return type?
Upvotes: 1
Views: 124
Reputation: 2310
You can do this
public static class Extensions
{
public static T ToEnum<T>(this string s) where T : struct
{
return (T)Enum.Parse(typeof(T), s);
}
}
public enum TestEnum
{
None,
Special,
}
class Program
{
static void Main(string[] args)
{
var x = TestEnum.Special.ToString();
var y = x.ToEnum<TestEnum>(); // y will be TestEnum.Special
}
}
Upvotes: 4
Reputation: 1387
Yes, it's possible, juste remove the second parameter of your method (it's totally useless) ans it will work (I tested the code) !
Upvotes: 1
Reputation: 834
Sure, you can do it like this:
public static T ToEnum<T>(this string s)
{
return (T)Enum.Parse(typeof(T), s);
}
Then you call it like this:
string s = "Red";
Color color = s.ToEnum<Color>();
Upvotes: 1