Re: Passing enumerator as generic type

Tech-Archive recommends: Fix windows errors by optimizing your registry



Since ImageSelection turns in MyImages it should work? But the compiler is
unfortunately treating it like a generic object. Maybe I can use
reflection to get the value of the enum? (I'd like a compile time solution
if possible.

Since you can't have a static interface in .NET (enum constants are static
members), you can't do this compile-time.

If you use reflection you probably want to cache the result, then your
performance hit won't be so bad and you can regain some type safety by
encapsulating the casts.

something like:

static class DefaultFor<TEnum>
{
private static initonly TEnum defvalue;
static DefaultFor()
{
// extra error-checking might be good
defvalue = (TEnum) typeof(TEnum).GetFields("Default",
MemberBinding.Static | MemberBinding.Public)[0].GetValue(null);
}
public static TEnum Value { get { return defvalue; } }
}

Now you can refer to DefaultFor<TEnum>.Value instead of TEnum.Default, a
little more clunky but not bad.


Thanks,
Jon




.



Relevant Pages

  • Re: Datatype of an enum
    ... >> enumeration without using reflection. ... If you have an enum variable, ... The thing is I'm trying to create a groupbox that acts much like the ... // The InitializeComponentcall is required for Windows Forms designer ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: values() of an Enumeration type that is a generic parameter?
    ... an enum), so reflection isn't needed anyway. ... The Class object, of course! ...
    (comp.lang.java.programmer)
  • Re: Reflection, Enums and their values?
    ... reference to Q001 when you're building your library; however, you still don't need to use reflection. ... that you need (Just realize that the Enum methods themselves probably use reflection, ...
    (microsoft.public.dotnet.framework)
  • Re: Reflection, Enums and their values?
    ... Using Reflection, I am able to look at the properties of that class, ... Use Type.GetMembers() on the Enum type to get the members. ... include all of the enumerators and a couple others with funny names (sorry, ...
    (microsoft.public.dotnet.framework)