Note that there are some explanatory texts on larger screens.

plurals
  1. POEnumerating Strings as bytes?
    primarykey
    data
    text
    <p>I was looking for a way to enumerate String types in (vb).NET, but .NET enums only accept numeric type values.</p> <p>The first alternative I came across was to create a dictionary of my enum values and the string I want to return. This worked, but was hard to maintain because if you changed the enum you would have to remember to also change the dictionary.</p> <p>The second alternative was to set field attributes on each enum member, and retrieve it using reflection. Surely enough this worked aswell and also solved the maintenance problem, but it uses reflection and I've always read that using reflection should be a last resort thing.</p> <p>So I started thinking and I came up with this: every ASCII character can be represented as a hexadecimal value, and you can assign hexadecimal values to enum members. You could get rid of the attributes, assign the hexadecimal values to the enum members. Then, when you need the text value, convert the value to a byte array and use <code>System.Text.Encodings.ASCII.GetString(enumMemberBytes)</code> to get the string value.</p> <p>Now speaking out of experience, anything I come up with is usually either flawed or just plain wrong. What do you guys think about this approach? Is there any reason not to do it like that?</p> <p>Thanks.</p> <p><strong>EDIT</strong></p> <p>As pointed out by David W, enum member values are limited in length, depending on the underlying type (integer by default). So yes, I believe my method works but you are limited to characters in the <a href="http://www.asciitable.com/" rel="nofollow">ASCII table</a>, with a maximum length of 4 or 8 characters using integers or longs respectively.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload