Good afternoon, let's say I have the enum
public enum Test : int
{
TestValue1 = 0,
TestValue2,
TestValue3
}
Why can't I use statements like Int32 IntTest = Test.TestValue1
without a cast to mean IntTest = 0
? It would be useful if I decided later to add more items to the enumeration? I think I am forced to use Int32 IntTest = (Int32) Test.TestValue1
, which I think should be redundant... Also, why can't I make something like
switch (IntTest)
{
case (Test.TestValue1) : DoSomething();
break;
case (Test.TestValue2) : DoSomethingElse();
break;
default : Do Nothing();
}
? The compiler says it expects a constant value in the place of TestValue1
... Isn't that value aready constant?
Thank you very much.
Overview. To convert an enum to int , we can: Typecast the enum value to int . Use the ToInt32 method of the Convert class.
Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.
No, we can have only strings as elements in an enumeration.
In C, each enumeration constant has type int and each enumeration type is compatible with some integer type. (The integer types include all three character types–plain, signed, and unsigned.) The choice of compatible type is implementation-defined.
I wanted to implement an enum in the same way as this to simply make it easier to convert an application using table column names as strings to indexes.
This is what I'm trying to achieve:
enum TableName
{
Column1Name = 0
}
Column1Data = (cast)objData[RowIndex][TableName.Column1Name];
the trouble as mentioned above is that C# requires an explicit cast when using enum's
Column1Data = (cast)objData[RowIndex][(int)TableName.Column1Name]; //what a waste of time..
But I've got a workaround.. moan all you want :P (this is not a production application - please think carefully about the impact of this code before implementing it in a live environment)
public static class TableName
{
public const int Column1Name = 0;
}
Column1Data = (cast)objData[RowIndex][TableName.Column1Name]; //this is now valid, and my sanity remains intact - as does the integer value ;)
Note that you can do this:
switch ((Test)IntTest)
{
case (Test.TestValue1) : DoSomething();
break;
case (Test.TestValue2) : DoSomethingElse();
break;
default : DoNothing();
}
The cast to Test from int is guaranteed not to fail, even if the value is not present in the enumeration. If the value is not present in the enumeration, calling ToString() on the Test instance will return the string representation of the underlying numeric value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With