Should we ever create enums? (C#, maybe valid for C++)
-
The title os this message might look like a joke, but it is actually very serious. The other day I wanted to implement my own
BigInteger
class, and I was usingbyte
s as the backing fields. Yet, I would only use values from 0 to 9 for each digit. Bing AI suggested me to create an enum with values ranging fromD0
toD9
(I think their actual values are obvious). Yet, using an enum like that doesn't forbid users from doing things like(DecimalDigit)56
and pass 56 to an enum that was only supposed to support values ranging from 0 to 9. Of course I can validate the values at run-time... but the entire purpose of using an enum was to avoid mistakes like that. So, my solution was to create aclass
(in fact, astruct
, but a class serves the same purpose) that has a private constructor, and haspublic static readonly
fields ranging from D0 to D9. This way, users outside of the class, except if they really want to mess up (like using unsafe reflection) cannot pass values that aren't in the 0-9 range. This also reminded me of a job where we had one enum with like 20 values... and then, many, many, many switches to get the many different traits of those enums. Wouldn't it be better to just have classes, with all the traits, and use the classes? Aside from the use of the enum inswitch
statements, they work the same in most cases, work even easier in cases where we usually had to use helper methods... and if a new trait is added, we have a single place (where the enum values are declared) to fix... with no chance of "forgetting" acase
in aswitch
somewhere else. What do you guys think? Example:public struct DecimalDigit
{
public static readonly DecimalDigit D0 = new(0);
public static readonly DecimalDigit D1 = new(1);
public static readonly DecimalDigit D2 = new(2);
public static readonly DecimalDigit D3 = new(3);
public static readonly DecimalDigit D4 = new(4);
public static readonly DecimalDigit D5 = new(5);
public static readonly DecimalDigit D6 = new(6);
public static readonly DecimalDigit D7 = new(7);
public static readonly DecimalDigit D8 = new(8);
public static readonly DecimalDigit D9 = new(9);private DecimalDigit(byte value)
{
_value = value;
}private readonly byte _value;
public byte ByteValue
{
get => _value;
}
}// vs
public enum DecimalDigit:
b -
The title os this message might look like a joke, but it is actually very serious. The other day I wanted to implement my own
BigInteger
class, and I was usingbyte
s as the backing fields. Yet, I would only use values from 0 to 9 for each digit. Bing AI suggested me to create an enum with values ranging fromD0
toD9
(I think their actual values are obvious). Yet, using an enum like that doesn't forbid users from doing things like(DecimalDigit)56
and pass 56 to an enum that was only supposed to support values ranging from 0 to 9. Of course I can validate the values at run-time... but the entire purpose of using an enum was to avoid mistakes like that. So, my solution was to create aclass
(in fact, astruct
, but a class serves the same purpose) that has a private constructor, and haspublic static readonly
fields ranging from D0 to D9. This way, users outside of the class, except if they really want to mess up (like using unsafe reflection) cannot pass values that aren't in the 0-9 range. This also reminded me of a job where we had one enum with like 20 values... and then, many, many, many switches to get the many different traits of those enums. Wouldn't it be better to just have classes, with all the traits, and use the classes? Aside from the use of the enum inswitch
statements, they work the same in most cases, work even easier in cases where we usually had to use helper methods... and if a new trait is added, we have a single place (where the enum values are declared) to fix... with no chance of "forgetting" acase
in aswitch
somewhere else. What do you guys think? Example:public struct DecimalDigit
{
public static readonly DecimalDigit D0 = new(0);
public static readonly DecimalDigit D1 = new(1);
public static readonly DecimalDigit D2 = new(2);
public static readonly DecimalDigit D3 = new(3);
public static readonly DecimalDigit D4 = new(4);
public static readonly DecimalDigit D5 = new(5);
public static readonly DecimalDigit D6 = new(6);
public static readonly DecimalDigit D7 = new(7);
public static readonly DecimalDigit D8 = new(8);
public static readonly DecimalDigit D9 = new(9);private DecimalDigit(byte value)
{
_value = value;
}private readonly byte _value;
public byte ByteValue
{
get => _value;
}
}// vs
public enum DecimalDigit:
bI use .IsDigit more often than defining what one is. Enums make code more readable. And can save storage.
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
-
The title os this message might look like a joke, but it is actually very serious. The other day I wanted to implement my own
BigInteger
class, and I was usingbyte
s as the backing fields. Yet, I would only use values from 0 to 9 for each digit. Bing AI suggested me to create an enum with values ranging fromD0
toD9
(I think their actual values are obvious). Yet, using an enum like that doesn't forbid users from doing things like(DecimalDigit)56
and pass 56 to an enum that was only supposed to support values ranging from 0 to 9. Of course I can validate the values at run-time... but the entire purpose of using an enum was to avoid mistakes like that. So, my solution was to create aclass
(in fact, astruct
, but a class serves the same purpose) that has a private constructor, and haspublic static readonly
fields ranging from D0 to D9. This way, users outside of the class, except if they really want to mess up (like using unsafe reflection) cannot pass values that aren't in the 0-9 range. This also reminded me of a job where we had one enum with like 20 values... and then, many, many, many switches to get the many different traits of those enums. Wouldn't it be better to just have classes, with all the traits, and use the classes? Aside from the use of the enum inswitch
statements, they work the same in most cases, work even easier in cases where we usually had to use helper methods... and if a new trait is added, we have a single place (where the enum values are declared) to fix... with no chance of "forgetting" acase
in aswitch
somewhere else. What do you guys think? Example:public struct DecimalDigit
{
public static readonly DecimalDigit D0 = new(0);
public static readonly DecimalDigit D1 = new(1);
public static readonly DecimalDigit D2 = new(2);
public static readonly DecimalDigit D3 = new(3);
public static readonly DecimalDigit D4 = new(4);
public static readonly DecimalDigit D5 = new(5);
public static readonly DecimalDigit D6 = new(6);
public static readonly DecimalDigit D7 = new(7);
public static readonly DecimalDigit D8 = new(8);
public static readonly DecimalDigit D9 = new(9);private DecimalDigit(byte value)
{
_value = value;
}private readonly byte _value;
public byte ByteValue
{
get => _value;
}
}// vs
public enum DecimalDigit:
bYour
DecimalDigit
struct
should be marked asreadonly
, since it will never be mutated. You could also replace the backing field with a read-only auto property. You'll probably want to implementIEquatable<T>
, and possiblyIComparable<T>
. And overrideToString
. At which point, it might be better to use areadonly record struct
. And after all that, without having to resort to reflection or unsafe code, you can still create an invalid instance:ReadOnlySpan span = new byte[] { 42 };
DecimalDigit digit = System.Runtime.InteropServices.MemoryMarshal.Read<DecimalDigit>(span);
Console.WriteLine(digit.ByteValue); // 42
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
Your
DecimalDigit
struct
should be marked asreadonly
, since it will never be mutated. You could also replace the backing field with a read-only auto property. You'll probably want to implementIEquatable<T>
, and possiblyIComparable<T>
. And overrideToString
. At which point, it might be better to use areadonly record struct
. And after all that, without having to resort to reflection or unsafe code, you can still create an invalid instance:ReadOnlySpan span = new byte[] { 42 };
DecimalDigit digit = System.Runtime.InteropServices.MemoryMarshal.Read<DecimalDigit>(span);
Console.WriteLine(digit.ByteValue); // 42
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
Thanks, I forgot I can make the entire struct final. Yet, I wouldn't get rid of the backing field... I don't like to make a class/struct use property getters instead of using their fields directly... that's really a personal choice. In any case, I will mark the struct as readonly. Thanks for reminding me of that!
-
Your
DecimalDigit
struct
should be marked asreadonly
, since it will never be mutated. You could also replace the backing field with a read-only auto property. You'll probably want to implementIEquatable<T>
, and possiblyIComparable<T>
. And overrideToString
. At which point, it might be better to use areadonly record struct
. And after all that, without having to resort to reflection or unsafe code, you can still create an invalid instance:ReadOnlySpan span = new byte[] { 42 };
DecimalDigit digit = System.Runtime.InteropServices.MemoryMarshal.Read<DecimalDigit>(span);
Console.WriteLine(digit.ByteValue); // 42
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
Question... if I have an array of my struct... the array itself is readonly... yet I can modify the contents of the array... should I mark the class readonly because I never replace one array by another, or not, as there are mutator methods to change the contents of the inner array?
-
Question... if I have an array of my struct... the array itself is readonly... yet I can modify the contents of the array... should I mark the class readonly because I never replace one array by another, or not, as there are mutator methods to change the contents of the inner array?
You can't mark a class as
readonly
; only astruct
. And astruct
containing an array ofstruct
s is probably a bad idea - the entire array would need to be stored inline as part of the outerstruct
s data. :)
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
The title os this message might look like a joke, but it is actually very serious. The other day I wanted to implement my own
BigInteger
class, and I was usingbyte
s as the backing fields. Yet, I would only use values from 0 to 9 for each digit. Bing AI suggested me to create an enum with values ranging fromD0
toD9
(I think their actual values are obvious). Yet, using an enum like that doesn't forbid users from doing things like(DecimalDigit)56
and pass 56 to an enum that was only supposed to support values ranging from 0 to 9. Of course I can validate the values at run-time... but the entire purpose of using an enum was to avoid mistakes like that. So, my solution was to create aclass
(in fact, astruct
, but a class serves the same purpose) that has a private constructor, and haspublic static readonly
fields ranging from D0 to D9. This way, users outside of the class, except if they really want to mess up (like using unsafe reflection) cannot pass values that aren't in the 0-9 range. This also reminded me of a job where we had one enum with like 20 values... and then, many, many, many switches to get the many different traits of those enums. Wouldn't it be better to just have classes, with all the traits, and use the classes? Aside from the use of the enum inswitch
statements, they work the same in most cases, work even easier in cases where we usually had to use helper methods... and if a new trait is added, we have a single place (where the enum values are declared) to fix... with no chance of "forgetting" acase
in aswitch
somewhere else. What do you guys think? Example:public struct DecimalDigit
{
public static readonly DecimalDigit D0 = new(0);
public static readonly DecimalDigit D1 = new(1);
public static readonly DecimalDigit D2 = new(2);
public static readonly DecimalDigit D3 = new(3);
public static readonly DecimalDigit D4 = new(4);
public static readonly DecimalDigit D5 = new(5);
public static readonly DecimalDigit D6 = new(6);
public static readonly DecimalDigit D7 = new(7);
public static readonly DecimalDigit D8 = new(8);
public static readonly DecimalDigit D9 = new(9);private DecimalDigit(byte value)
{
_value = value;
}private readonly byte _value;
public byte ByteValue
{
get => _value;
}
}// vs
public enum DecimalDigit:
bPaulo Zemek wrote:
to implement my own BigInteger class,
Idea: add information to your post about why you want/need to do this. What functionality does the MS BigInteger Struct provide that you need extended, modified, etc. [^] ? [^]
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
-
Your
DecimalDigit
struct
should be marked asreadonly
, since it will never be mutated. You could also replace the backing field with a read-only auto property. You'll probably want to implementIEquatable<T>
, and possiblyIComparable<T>
. And overrideToString
. At which point, it might be better to use areadonly record struct
. And after all that, without having to resort to reflection or unsafe code, you can still create an invalid instance:ReadOnlySpan span = new byte[] { 42 };
DecimalDigit digit = System.Runtime.InteropServices.MemoryMarshal.Read<DecimalDigit>(span);
Console.WriteLine(digit.ByteValue); // 42
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
The real class implements IEquatable and IComparable. I simply didn't want to make the code to huge for this discussion. And, even though Marshal methods aren't marked as unsafe they are, by definition, unsafe. In fact, reflection itself is not called unsafe, although you can create empty instances of classes that do not define default constructors and the like...
-
The title os this message might look like a joke, but it is actually very serious. The other day I wanted to implement my own
BigInteger
class, and I was usingbyte
s as the backing fields. Yet, I would only use values from 0 to 9 for each digit. Bing AI suggested me to create an enum with values ranging fromD0
toD9
(I think their actual values are obvious). Yet, using an enum like that doesn't forbid users from doing things like(DecimalDigit)56
and pass 56 to an enum that was only supposed to support values ranging from 0 to 9. Of course I can validate the values at run-time... but the entire purpose of using an enum was to avoid mistakes like that. So, my solution was to create aclass
(in fact, astruct
, but a class serves the same purpose) that has a private constructor, and haspublic static readonly
fields ranging from D0 to D9. This way, users outside of the class, except if they really want to mess up (like using unsafe reflection) cannot pass values that aren't in the 0-9 range. This also reminded me of a job where we had one enum with like 20 values... and then, many, many, many switches to get the many different traits of those enums. Wouldn't it be better to just have classes, with all the traits, and use the classes? Aside from the use of the enum inswitch
statements, they work the same in most cases, work even easier in cases where we usually had to use helper methods... and if a new trait is added, we have a single place (where the enum values are declared) to fix... with no chance of "forgetting" acase
in aswitch
somewhere else. What do you guys think? Example:public struct DecimalDigit
{
public static readonly DecimalDigit D0 = new(0);
public static readonly DecimalDigit D1 = new(1);
public static readonly DecimalDigit D2 = new(2);
public static readonly DecimalDigit D3 = new(3);
public static readonly DecimalDigit D4 = new(4);
public static readonly DecimalDigit D5 = new(5);
public static readonly DecimalDigit D6 = new(6);
public static readonly DecimalDigit D7 = new(7);
public static readonly DecimalDigit D8 = new(8);
public static readonly DecimalDigit D9 = new(9);private DecimalDigit(byte value)
{
_value = value;
}private readonly byte _value;
public byte ByteValue
{
get => _value;
}
}// vs
public enum DecimalDigit:
bSkipping the class/struct/readonly/whatever discussions, and commenting on the subject line topic: Enums. My programming childhood (i.e. as a university freshman) was with Pascal, which provided true enums. Not named integers. In the C language class, replacing integer #define with enum is just syntactical sugar. They are integers in disguise. Or not really disguise - it is just a very thin veil. The very idea behind enums is that they are not integers, no matter what C programmers say. January, February and so on are months, not integers! May is May. It takes a C programmer to get into an argument whether the month of May "really" is 4 or 5. Well, the C programmer would never be in doubt. Also, half of May is March, that is obvious, isn't it? (Half of June is also March.) Noooo! Enums are countable (enumerable, if you prefer). So are apples. That doesn't make an apple an integer. If you are really talking about integers, they are integers. Replacing the digit 0 with 'D0', 1 with 'D1' and so on does not, not in any way whatsoever, 'improve legibility'. Quite to the contrary; it hides the fact that you are in fact talking about integer numbers. The reader has to look up the definition of 'D4' to see what it represents: Is it the binary integer 4, or is is the character code for the '4' digit character, or something quite different, such as 'dictionary entry with key 4'? Enums have no place in this context of yours - not even in the C-style 'enums are named integers' style. You are handling true integers. Declare them as true integers, and nothing else. (And: If Pascal had still been alive, you could have had exactly what you are trying to achieve defining new subrange type such as TYPE SingleDigitInteger = 0 ..9; and the compiler + runtime system would catch all attempts to set a variable/field of this type to a value outside its defined range. It would still be a numeric integer. Unfortunately, Pascal, and a lot of great ideas it represented, died several decades ago.)
-
Skipping the class/struct/readonly/whatever discussions, and commenting on the subject line topic: Enums. My programming childhood (i.e. as a university freshman) was with Pascal, which provided true enums. Not named integers. In the C language class, replacing integer #define with enum is just syntactical sugar. They are integers in disguise. Or not really disguise - it is just a very thin veil. The very idea behind enums is that they are not integers, no matter what C programmers say. January, February and so on are months, not integers! May is May. It takes a C programmer to get into an argument whether the month of May "really" is 4 or 5. Well, the C programmer would never be in doubt. Also, half of May is March, that is obvious, isn't it? (Half of June is also March.) Noooo! Enums are countable (enumerable, if you prefer). So are apples. That doesn't make an apple an integer. If you are really talking about integers, they are integers. Replacing the digit 0 with 'D0', 1 with 'D1' and so on does not, not in any way whatsoever, 'improve legibility'. Quite to the contrary; it hides the fact that you are in fact talking about integer numbers. The reader has to look up the definition of 'D4' to see what it represents: Is it the binary integer 4, or is is the character code for the '4' digit character, or something quite different, such as 'dictionary entry with key 4'? Enums have no place in this context of yours - not even in the C-style 'enums are named integers' style. You are handling true integers. Declare them as true integers, and nothing else. (And: If Pascal had still been alive, you could have had exactly what you are trying to achieve defining new subrange type such as TYPE SingleDigitInteger = 0 ..9; and the compiler + runtime system would catch all attempts to set a variable/field of this type to a value outside its defined range. It would still be a numeric integer. Unfortunately, Pascal, and a lot of great ideas it represented, died several decades ago.)
You got it... the real purpose was to have a Range<0, 9>. That's something I can easily do in C++ templates... and it would avoid enums altogether... and also classes that act as enums.
-
The title os this message might look like a joke, but it is actually very serious. The other day I wanted to implement my own
BigInteger
class, and I was usingbyte
s as the backing fields. Yet, I would only use values from 0 to 9 for each digit. Bing AI suggested me to create an enum with values ranging fromD0
toD9
(I think their actual values are obvious). Yet, using an enum like that doesn't forbid users from doing things like(DecimalDigit)56
and pass 56 to an enum that was only supposed to support values ranging from 0 to 9. Of course I can validate the values at run-time... but the entire purpose of using an enum was to avoid mistakes like that. So, my solution was to create aclass
(in fact, astruct
, but a class serves the same purpose) that has a private constructor, and haspublic static readonly
fields ranging from D0 to D9. This way, users outside of the class, except if they really want to mess up (like using unsafe reflection) cannot pass values that aren't in the 0-9 range. This also reminded me of a job where we had one enum with like 20 values... and then, many, many, many switches to get the many different traits of those enums. Wouldn't it be better to just have classes, with all the traits, and use the classes? Aside from the use of the enum inswitch
statements, they work the same in most cases, work even easier in cases where we usually had to use helper methods... and if a new trait is added, we have a single place (where the enum values are declared) to fix... with no chance of "forgetting" acase
in aswitch
somewhere else. What do you guys think? Example:public struct DecimalDigit
{
public static readonly DecimalDigit D0 = new(0);
public static readonly DecimalDigit D1 = new(1);
public static readonly DecimalDigit D2 = new(2);
public static readonly DecimalDigit D3 = new(3);
public static readonly DecimalDigit D4 = new(4);
public static readonly DecimalDigit D5 = new(5);
public static readonly DecimalDigit D6 = new(6);
public static readonly DecimalDigit D7 = new(7);
public static readonly DecimalDigit D8 = new(8);
public static readonly DecimalDigit D9 = new(9);private DecimalDigit(byte value)
{
_value = value;
}private readonly byte _value;
public byte ByteValue
{
get => _value;
}
}// vs
public enum DecimalDigit:
b