Given a generic parameter TEnum which always will be an enum type, is there any way to cast from TEnum to int without boxing/unboxing?
See this example code. This w
...I'm even 'later' : )
but just to extend on the previous post (Michael B), which did all the interesting work
and got me interested into making a wrapper for a generic case (if you want to cast generic to enum actually)
...and optimized a bit... (note: the main point is to use 'as' on Func<>/delegates instead - as Enum, value types do not allow it)
public static class Identity
{
public static readonly Func Cast = (Func)((x) => x) as Func;
}
...and you can use it like this...
enum FamilyRelation { None, Father, Mother, Brother, Sister, };
class FamilyMember
{
public FamilyRelation Relation { get; set; }
public FamilyMember(FamilyRelation relation)
{
this.Relation = relation;
}
}
class Program
{
static void Main(string[] args)
{
FamilyMember member = Create(FamilyRelation.Sister);
}
static T Create(P value)
{
if (typeof(T).Equals(typeof(FamilyMember)) && typeof(P).Equals(typeof(FamilyRelation)))
{
FamilyRelation rel = Identity.Cast(value);
return (T)(object)new FamilyMember(rel);
}
throw new NotImplementedException();
}
}
...for (int) - just (int)rel