What is the best way to index an array by an enum. Pascal has a nice feature
in that arrays can be indexed by an enum, for example
type
ButtonType = ( Left, Middle, Right ) ;
var
buttons : array[ ButtonType ] of Button ;
....
buttons[ Left ].Enabled := true ;
It appears that the only way to do this in C# is to cast the enum into an
integer, eg
enum ButtonType { Left, Middle, Right ) ;
Button[] buttons = new Button[ (int) ButtonType.Righ t + 1 ] ;
......
buttons[ (int) ButtonType.Left ].Enabled = true ;
Apart from the fact that the C# code is a lot less elegant and looks messy
with all the horrible casting, it's also not possible for the compiler to
check properly. Also if it becomes necessary to add another item to the enum
then you have to go through all the code and change the array declarations
and make sure that you have taken care of all the places that need changing.
In Pascal the compiler would automatically get the array declarations right
and would also flag up cases where you would need to make changes to take
care of the extra enum, eg. when walking through all items in the array.
Is there a better way of doing this in C#?
Has there been any discussion of adding arrays indexed by enums to the C#
language in the future?
Cheers
MikeS. 3 14729
"Mike Scott" <mi**@nospam.co m> wrote in message
news:er******** ******@TK2MSFTN GP10.phx.gbl...
Mike,
[cut] Button[] buttons = new Button[ (int) ButtonType.Righ t + 1 ] ;
[cut] check properly. Also if it becomes necessary to add another item to the
enum then you have to go through all the code and change the array declarations and make sure that you have taken care of all the places that need
changing.
In C# you can declare an array like this:
Button[] buttons =
new Button[System.Enum.Get Values(typeof(B uttonType)).Len gth]
Now, if you add/remove items from the enum, size of the array
should always be ok.
HTH,
Maciej
Mike,
The way I do this is to encapsulate the downcast. I create a new class that
has an indexer with a parameter of the Enum type. I would have a private
member that contained the actual array, or a hashtable depending on if the
enum had sparse numbers or not. (sparse enum = [Flags] enum ButtonType {
Left = 1, Middle =2 , Right = 4, Top = 8, Bottom = 16 })
I would have this new class implement either ICollection or IList depending
on how flexible I wanted it. Of course inheriting DictionaryBase would
simplify the code. Inheriting CollectionBase in this regard doesn't really
make sense, as we want it indexed by the Enum, not a dynamic collection.
You can use Enum.GetValues( ).Length or Enum.GetNames() .Length to find the
number of values in an enum, so in the constructor of the above class, you
would not need to 'hard code' the number of elements. Also a HashTable would
not be constrained by number of elements, and would support the
FlagsAttribute better.
Hope this helps
Jay
"Mike Scott" <mi**@nospam.co m> wrote in message
news:er******** ******@TK2MSFTN GP10.phx.gbl... What is the best way to index an array by an enum. Pascal has a nice
feature in that arrays can be indexed by an enum, for example
type ButtonType = ( Left, Middle, Right ) ;
var buttons : array[ ButtonType ] of Button ;
... buttons[ Left ].Enabled := true ;
It appears that the only way to do this in C# is to cast the enum into an integer, eg
enum ButtonType { Left, Middle, Right ) ;
Button[] buttons = new Button[ (int) ButtonType.Righ t + 1 ] ;
..... buttons[ (int) ButtonType.Left ].Enabled = true ;
Apart from the fact that the C# code is a lot less elegant and looks messy with all the horrible casting, it's also not possible for the compiler to check properly. Also if it becomes necessary to add another item to the
enum then you have to go through all the code and change the array declarations and make sure that you have taken care of all the places that need
changing. In Pascal the compiler would automatically get the array declarations
right and would also flag up cases where you would need to make changes to take care of the extra enum, eg. when walking through all items in the array.
Is there a better way of doing this in C#?
Has there been any discussion of adding arrays indexed by enums to the C# language in the future?
Cheers
MikeS.
Hi Jay,
Unfortunately Enum.GetValues( ) and Enum.GetNames() are not supported on the
Compact Framework :-(
Also it's a bit of a chore to have to create a whole wrapper class just to
create a little array indexed by an enum - A one line declaration in Pascal
:-(
Cheers
MikeS.
"Jay B. Harlow [MVP - Outlook]" <Ja********@ema il.msn.com> wrote in message
news:e9******** ******@TK2MSFTN GP10.phx.gbl... Mike, The way I do this is to encapsulate the downcast. I create a new class
that has an indexer with a parameter of the Enum type. I would have a private member that contained the actual array, or a hashtable depending on if the enum had sparse numbers or not. (sparse enum = [Flags] enum ButtonType { Left = 1, Middle =2 , Right = 4, Top = 8, Bottom = 16 })
I would have this new class implement either ICollection or IList
depending on how flexible I wanted it. Of course inheriting DictionaryBase would simplify the code. Inheriting CollectionBase in this regard doesn't really make sense, as we want it indexed by the Enum, not a dynamic collection.
You can use Enum.GetValues( ).Length or Enum.GetNames() .Length to find the number of values in an enum, so in the constructor of the above class, you would not need to 'hard code' the number of elements. Also a HashTable
would not be constrained by number of elements, and would support the FlagsAttribute better.
Hope this helps Jay
"Mike Scott" <mi**@nospam.co m> wrote in message news:er******** ******@TK2MSFTN GP10.phx.gbl... What is the best way to index an array by an enum. Pascal has a nice feature in that arrays can be indexed by an enum, for example
type ButtonType = ( Left, Middle, Right ) ;
var buttons : array[ ButtonType ] of Button ;
... buttons[ Left ].Enabled := true ;
It appears that the only way to do this in C# is to cast the enum into
an integer, eg
enum ButtonType { Left, Middle, Right ) ;
Button[] buttons = new Button[ (int) ButtonType.Righ t + 1 ] ;
..... buttons[ (int) ButtonType.Left ].Enabled = true ;
Apart from the fact that the C# code is a lot less elegant and looks
messy with all the horrible casting, it's also not possible for the compiler
to check properly. Also if it becomes necessary to add another item to the enum then you have to go through all the code and change the array
declarations and make sure that you have taken care of all the places that need changing. In Pascal the compiler would automatically get the array declarations
right and would also flag up cases where you would need to make changes to
take care of the extra enum, eg. when walking through all items in the array.
Is there a better way of doing this in C#?
Has there been any discussion of adding arrays indexed by enums to the
C# language in the future?
Cheers
MikeS.
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Jens Thiede |
last post by:
Quick-Fix: Can preg_match_all return the indexes of where it matched the
string?
More Detail: Read carefully: I'd like to seperate a string's parts into two
(2) arrays which can be subdivide themselves. Then modify them and glue
them back together. I will refer to the two arrays as highlight and
remnants. The method I'm using to glue the string together correctly is to
store the string indexes (positions) of both the highlight and...
|
by: Hilde Roth |
last post by:
This may have been asked before but I can't find it. If I have
a rectangular list of lists, say, l = ,,], is
there a handy syntax for retrieving the ith item of every sublist?
I know about for i in l] but I was hoping for something more
like l.
Hilde
|
by: Michael Drumheller |
last post by:
(If you're not interested in NumArray, please skip this message.)
I am new to NumArray and I wonder if someone can help me with
array-indexing. Here's the basic situation: Given a rank-2 array
(i.e., a matrix) it seems to be trivial, with array indexing,
to extract a subset of its *columns*. But it does not seem
to be trivial to extract a subset of its *rows*. The code
snippet below describes the problem (if it really is a problem)...
|
by: SpaceCowboy |
last post by:
I recently got into a discussion with a co-worker about using enums across a
dll interface. He wanted to use chars instead, argueing that depending on
compiler settings the size of an enum could change and lead to memory
corruption. I didn't see how this was possible. He claims that if a dll
built for a program is built with different compiler settings than the
launcher program, the enum size could change.
The only way I could figure...
|
by: Faisal |
last post by:
Can anyone tell me if it is possible to enumerate through all the Enums within a class . I have a class with many Enums and would like to accees the Enums through an array/collection etc. I can't seem to find an appropriate Reflection method to access Enums within a class
I would like to loop through the Enums in the 'Foo' Class retrieve the Enums 'Car' and 'House
Public Class Fo
Public Enum Ca
For
Chevrole
Toyot
| |
by: Martin Pritchard |
last post by:
Hi,
I'm working on a project that historically contains around 40 enums. In the
database various fields refer to the int values of these enums, but of
course ref integrity is not enofrced and when looking at the db we can't
tell what the value in a field represents. The other problem is that our
enums are currently all stored in a single class, which means that because
of no visibility constraints the enums are often used out of context...
|
by: John [H2O] |
last post by:
I'm having trouble slicing arrays:
I thought I could do the following:
Traceback (most recent call last):
File "<string>", line 1, in <string>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
It's strange, because I can do this:
|
by: Terry Reedy |
last post by:
John wrote:
If these are numpy arrays, as appears, rather that array module arrays,
then the numpy list might be a better place. In any case, using 'numpy'
would have gotten the attention of someone scanning for posts about numpy.
|
by: Soren |
last post by:
Hi,
I'm trying to make a weave python extension to use in my program. I
already did it in inline, but that doesn't work with py2exe (needs
compiler), so I'm creating extensions instead using ext_tools.
Is there a way I can use blitz with ext_tools? so that I can refer to
arrays like a(x,y) in the c code?? I have alot of 2D arrays that needs
indexing in the C code..
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |