-2

I'm trying to do something like this..

enum Birds {
    Crow,
    Sparrow,
    Hawk
}

enum Bugs {
    Ant,
    Spider,
    Scorpion
}

if (featherless == true) {
    var beast = Bugs;
} else {
    var beast = Birds;
}

string a = (beast)2.ToString();

I have five lines of code that works on the provided enum. I can't imagine that I have to duplicate these five lines.. something like the above must be able to be used... The above structure of course causes beast to be out of scope and I can't pass var as a parameter. I know this is a headsmack moment, but I've searched and can't find a similar question.

Todd Painton
  • 701
  • 7
  • 20
  • 1
    It's not clear what you're actually trying to achieve - or what you mean by "I can't pass var as a parameter" when you don't have any method calls to have parameters anyway... – Jon Skeet May 28 '15 at 05:10
  • 1
    If you mean how can I assign `Beast` to either one of the `Bug` enums, or one of the `Birds` have a look at a work around for [C#'s lack of enum inheritance / case classes](http://stackoverflow.com/q/757684/314291) – StuartLC May 28 '15 at 05:11
  • `var` is not variable in type. it's variable in value. – RadioSpace May 28 '15 at 05:17
  • Thanks we appreciate your input. – Todd Painton May 28 '15 at 13:28

1 Answers1

2
var beastType = featherless ? typeof(Bugs) : typeof(Birds);
var a = Enum.GetValues(beastType).GetValue(2).ToString();

Will assign Hawk if featherless is true or Scorpion if it's false.

Edit 0 Maybe this will be a better solution if you only need the name:

var beastType = featherless ? typeof(Bugs) : typeof(Birds);
var a = Enum.GetName(beastType, 2);

Edit 1 Maybe you can try this if you need an object for further operations:

var beastType = featherless ? typeof(Bugs) : typeof(Birds);
var beast = Enum.ToObject(beastType, 2);
var a = beast.ToString();
Sebastian Schumann
  • 3,204
  • 19
  • 37
  • BRILLIANT. Thank you soooo much. I also really appreciate you not askign WHY I would like to do such a thing. I'm removing the following comment from my code. /* Yes, well aware this is duplicate code but the really really smart ones at StackOverflow were more interested in critiquing a question than finding a solution to it */ Your solution does exact why my pseudo code was trying to accopmplish and more. I'm still pissed about two lame down votes. Totally not called for. – Todd Painton May 28 '15 at 12:22