-2

Consider the following

class Body
{
    [Flags]
    enum Organs { None = 0, Brain = 1, Heart = 2, Kidney = 4, Skin = 8 }

    Organs damagedOrgan = Organs.Heart;
    Organs currentOrgan = Organs.Kidney;
    Organs favoriteOrgan = Organs.Brain;
    Organs biggestOrgan = Organs.Skin;
    Organs allOrgans = Organs.Heart | Organs.Kidney | Organs.Brain | Organs.Skin;
}

Could in certain cases be much more clean to just write as such:

using static Human.Body.Organs;

class Body
{
    [Flags]
    enum Organs { None = 0, Brain = 1, Heart = 2, Kidney = 4, Skin = 8 }

    Organs damagedOrgan = Heart;
    Organs currentOrgan = Kidney;
    Organs favoriteOrgan = Brain;
    Organs biggestOrgan = Skin;
    Organs allOrgans = Heart | Kidney | Brain | Skin;

}

This will however generate the following error.

Error CS0122 'Body.Organs' is inaccessible due to its protection level

Is there any way to have a using static block on an enum in a class contained (private) enum to avoid having to excessively name the enum?

jsmars
  • 1,640
  • 5
  • 21
  • 33
  • 1
    Make it `public`? Does it have to be `private`? – CoolBots Sep 11 '20 at 06:52
  • 5
    Short answer: no. The docs on `using static` make it clear it only imports accessible members, and `using static` is only allowed at the top level. Ergo, you can't use it on inaccessible types, regardless of whether they're `enums` or nested. – Jeroen Mostert Sep 11 '20 at 06:52
  • Note you can shorten the last line considerably but defining `allOrgans` as a member of the enum itself – Aluan Haddad Sep 11 '20 at 07:13
  • @CoolBots yes I would like to be able to do it for private members, I know I can do it for publit members :) – jsmars Sep 11 '20 at 08:32
  • @JeroenMostert Thanks this answers my question though I wish it was supported – jsmars Sep 11 '20 at 08:33
  • @AluanHaddad Thanks I'm aware of this also, this is just for the example. – jsmars Sep 11 '20 at 08:33
  • I'm sure, I was just thinking of a way you could increase brevity because that seems to be your objective. Otherwise, I would just make the enum internal – Aluan Haddad Sep 11 '20 at 08:35

2 Answers2

2

using static will only work on accessible members - so private enum is out. However, it depends on how private you want your enum to be. If you're ok with making it internal, that'll work.

CoolBots
  • 4,770
  • 2
  • 16
  • 30
  • Thanks, though I would prefer to have it private, having it as an internal is a nice workaround! – jsmars Sep 11 '20 at 08:34
0

Make your class and enum public..

I suppose if you want your enum to remain private you might not care so much about its name (as it will be limited in scope and no one else will see it) so you could shorten Organs to O and dispense with the using static

Caius Jard
  • 72,509
  • 5
  • 49
  • 80