Thursday, 15 August 2013

c# 4.0 - Extension and enum type -



c# 4.0 - Extension and enum type -

i trying add together extension method enum type code below fail. compiler gives error on line storetype.getallitems how add together extension method enum type?

namespace consoleapplication1 { public static class enumextensions { public static ienumerable<t> getallitems<t>(this enum value) { foreach (object item in enum.getvalues(typeof(t))) { yield homecoming (t)item; } } } class programme { [flags] public enum storetype { paypal = 1, plimus = 2, other = 3 }; static void main(string[] args) { storetype.getallitems //fail here } } }

you have phone call getallitems on value, not type:

storetype.paypal.getallitems()

but wouldn't improve not create extension method en declare as:

public static class enumextensions { public static ienumerable<t> getallitems<t>() { foreach (object item in enum.getvalues(typeof(t))) { yield homecoming (t)item; } } } static void main(string[] args) { var allenumitems = enumextensions.getallitems<storetype>() }

or even:

enum.getvalues(typeof (storetype)); enum.getnames(typeof (storetype));

after can utilize enum.tryparse(...) parse names enums, think want?

c#-4.0 enums extension-methods

No comments:

Post a Comment