简体   繁体   中英

Passing by enum class variables in C# via parameters to a function

I'm very confused here. Suppose I have two programs in Visual Studios - I'm using C# WPF. Suppose I have two programs where Program 1 has Program 2 as a reference - and similarly Program 2 has Program 1 as a reference.

Program1.sol

p1.xaml.cs contents:

public void checkStuff(myThing x)
{
   // Do stuff (irrelevant)
}

public enum myThing
{
  stuff,
  stuff2,
  stuff3,
  stuff4
}

Program2.sol

p2.xaml.cs contents:

// Let's say I call that function
p1 p1content = new p1();
p1content.checkStuff(0); // <-- Why does this work??

My question is, why does the number 0 work as a parameter? This may be trivial but what exactly does the program think I am passing in that function when I pass in 0? At first I thought it was the index of the variables located in my enum class, but it can't be because I can't pass in 1,2, or 3, etc..

By default in C# the underlying type of enum s are int . See the MSDN documentation .

As mentioned in the comment in this SO post :

The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char.

An enum has an integer-based value as base (int, byte, ulong, etc). The compiler only accepts an assigment of zero to guarantee an variable of an enum-based type to be initialized even when no explicit value has been assigned to the enum attributes. The compiler however does not accept any other values. This is a build-in safety, but more so a compromise of addressing a flaw in the compiler design to resolve previous inconsistent behavior with enums. This little story by Eric Lippert provides an insight into how this came into existence.

When you declare an enum such as the one in your question, what actually happens under the hood(ish) is this:

public enum myThing : int
{
  stuff = 0,
  stuff2 = 1,
  stuff3 = 2,
  stuff4 = 3
}

ie, the default, underlying type of an enum is an int , and the fields are started sequentially from zero.

Strangely, this only works for the zero element, for example this works:

checkStuff(0);

but this will not

checkStuff(1); //error

You would need to be explicit

checkStuff((myThing)1); //cast int to myThing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM