Click here to Skip to main content
15,886,110 members
Everything / Enum

Enum

enum

Great Reads

by slavik57
Have you ever wanted to enumerate all the names and values of an enum? Now you can.
by Matteo Prosperi
This is the third post in the .NET libraries and the art of backward compatibility series.
by kb-boxer
Where enum does not work !!!
by ShlomiO
Dynamic 'Enum' like solution.

Latest Articles

by Matteo Prosperi
This is the third post in the .NET libraries and the art of backward compatibility series.
by Mike-MadBadger
What responses to expect from the enum.IsDefined method in .NET given a variety of inputs
by robsosno
Replacement for standard enums with additional functionality.
by slavik57
Have you ever wanted to enumerate all the names and values of an enum? Now you can.

All Articles

Sort by Score

Enum 

1 Jan 2014 by Sergey Alexandrovich Kryukov
For a beginner, this is not so silly question, at least you formulated it correctly, which is so rare these days, my special thanks for that.Your idea to use bit-mapped enumeration type to describe the planet status in a compact and well-supportable way is good. Only the declaration could be...
13 Mar 2015 by manchanx
This:typeof(myEnum) doesn't work because myEnum is your enum variable, not your enum type.Instead you have to write the name of your enum-definition there - the equivalent to what is HemEnum in the source you linked:public enum HemEnum{ [Description("none")] HemNone = -1, ...
23 Jul 2016 by slavik57
Have you ever wanted to enumerate all the names and values of an enum? Now you can.
27 Aug 2019 by Maciej Los
You forgot to add a name of enum. Replace ths: enum { infinity=-1 }; with: enum name_of_enum_here { infinity=-1 }; See: Enumeration declaration - cppreference.com[^]
20 Jun 2014 by phil.o
Enumerations are serializable by nature (they are constant integer values). You don't have to bother :)Why not just making a simple trivial test to check it?Kind regards.
9 Sep 2015 by CPallini
Quote:std::string ERROR(std::string*);Wrong: if you give the name of the class to an ordinary method, then the compiler considers it a constructor, but constructors must NOT have return values.Quote:td::string ERROR::ERROR(ERROR::ENUM_ERROR error)Wrong: there is no declaration for this...
19 Aug 2021 by Richard Deeming
Unfortunately, there isn't a non-generic overload of TryParse. Which means you'll need to use some reflection to invoke the method. For example: public static class EnumExtensions { public static bool TryParse(Type enumType, string value,...
15 Nov 2013 by Sergey Alexandrovich Kryukov
You already did it here: how to set propertise in the method?[^].After all, could you consider stopping to ask such non-productive question. First, read the manual and reference on the basic language and .NET features, and ask the questions only you had a good reading, tried hard to write...
18 Nov 2013 by phil.o
You can play with enums this way:monthToVal value = (monthToVal)2; // value will hold monthToVal.FEBstring name = monthToVal.ToString("g"); // name will hold "FEB"
18 Nov 2013 by Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)
Refer- Enum.GetName Method[^].You can do like below to get the Enum constant name from value.Enum.GetName(typeof(monthToVal), 2);
3 Mar 2014 by BillWoodruff
Yes, you can sort the values in an Enum for display in a ComboBox alpha-numerically, or any other way you want:// requires Linq// preserve the current ComboBox selectionprivate V currentVName;private void Form1_Load(object sender, EventArgs e){ var vAry =...
3 Nov 2015 by Richard Deeming
Override the Comparer property[^] with a custom IComparer instance that sorts as you want it to.Something like this should work:Class EnumDescriptionComparer : Implements IComparer Private ReadOnly _enumType As Type Public Sub New(ByVal enumType As Type) ...
4 Jun 2016 by OriginalGriff
Try:foreach (ProgramDeclaration val in Enum.GetValues(typeof(ProgramDeclaration))){ Console.WriteLine("Value : {0} and Integer Value : {1}", val, (int) val); }
4 Jun 2016 by Philippe Mori
For sure, you won't get an int if val is declared as an enumeration and there is an item in the enumeration for that value.If you want integer values, then get integer value! This is as simple as that!foreach (int val in Enum.GetValues(typeof(ProgramDeclaration))){ ...
20 Jun 2016 by KarstenK
To achieve your own sort order you must overwrite the sorting algorithm, by overwriting the comparison operator "
24 May 2019 by Gerry Schmitz
Days.Sun, for your purposes, is a "constant"; an enum value; which can only appear on the RIGHT side.
26 Oct 2020 by Matteo Prosperi
This is the third post in the .NET libraries and the art of backward compatibility series.
30 Jul 2010 by kb-boxer
Where enum does not work !!!
11 Jul 2011 by Sergey Alexandrovich Kryukov
Are you sure it was C++? Just in case: in November I published an article on the similar topic, but in .NET: Enumeration Types do not Enumerate! Working around .NET and Language Limitations[^].I don't thing enumeration type can be extended. The approach is to wrap it in a class using...
20 Oct 2011 by shoorrock
I'm working on a program that maps keystrokes to custom commands (for example Control+F2 executes a command. I want to allow my users to change the keystroke commands. What I've done is in process command key captures the key and checks for a shortcut against a keys dictionary.I need...
20 Nov 2011 by ShlomiO
Dynamic 'Enum' like solution.
3 Jul 2012 by Iranian MM
These are list your partitions :code : parted -landcode : fdisk -lare the same.andcode : cat /proc/partitionshave less information about partitions than fdisk -l and parted -l.code : lsusbdisplaying information about USB buses in the system and the devices connected to...
19 Jun 2013 by samadhan_kshirsagar
HIplease visit this linkhttp://stackoverflow.com/questions/943398/get-int-value-from-enum[^]
19 Jun 2013 by usman.aridian
try to use GetHashCode mehtod like below Console.WriteLine(hello.one.GetHasCode());
19 Jun 2013 by Aarti Meswania
Console.WriteLine((int)hello.o...
6 Aug 2013 by Fredrik Bornander
You still need to declare a name for parameter. Try changing it to;public enum attachmentType { filePath , fileString};public static void SendEmail(attachmentType type = attachmentType.filePath){ // Do stuff}Hope this helps,Fredrik
10 Aug 2013 by Clifford Nelson
I would look at the following article: Using DescriptionAttribute for enumerations bound to a ComboBox[^]
24 Aug 2013 by Mike-MadBadger
The .Net 4.5 Enum.IsDefined definition includes the following two statements which appear highly ambiguous to me.Definitionpublic static bool IsDefined( Type enumType, Object value)true if a constant in enumType has a value equal to value; otherwise,...
18 Nov 2013 by CPallini
You did not check out the documentation[^], did you?
5 Apr 2014 by Richard MacCutchan
It means that you have not created a constructor in your enum which takes a boolean value. You need to change it so it looks like: public enum Day { Monday(false), Tuesday(false), Wednesday(false), Thursday(false), Friday(false), ...
5 Apr 2014 by Sergey Alexandrovich Kryukov
This is the perfectly expected result. I described the phenomenon you observed in detail in my article where I also created some interesting work-around solution: Enumeration Types do not Enumerate! Working around .NET and Language Limitations.—SA
29 Aug 2014 by Member 9365518
Suppose we have this enum (in c#)enum Weekdays { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }And we need to do the following: Console.WriteLine(Weekdays.Sunday.ToString());Here are I get...
29 Aug 2014 by OriginalGriff
If you have two items that have the same value in an enum, it can;t tell which one you mean.Bear in mind that an enum is stored as an int, and the "names" are a syntactic sugar to make your code easier to read. The names do not "carry forward" with the values, if you say:Weekdays dayOne =...
7 Sep 2014 by Fredrik Bornander
It seems a little over-kill to create your own function for doing this, Enum.Parse (or Enum.TryParse) or even a CType call will do this for you.But if your circumstances are such that you need a generic method for this, then maybe something like this will do the trick for you;Module...
24 Apr 2018 by Kornfeld Eliyahu Peter
I used this set of declarations and all works well: public enum LoanIdentifierBase { NotSet, AgencyCase, InvestorCommitment, InvestorContract, InvestorLoan, InvestorWorkoutCase, LenderCase, LenderLoan } public...
21 Aug 2018 by willifritz
Fruit must have a parameterless constructor. Add public Fruit() { } to your Fruit class and var AllFruits2 = Fruit.GetAll(); should work.
24 May 2019 by User 11060979
Days.Sun = (int) 10;//error here Think about what you are trying to do here... "Days" is the enum and "Sun" is one of the enumeration values... Completly confusing... Do you like mabye to do something like this? int day= (int)Days.Sun Anyway what do you expect from the value '10' from an...
21 Sep 2019 by BillWoodruff
I think you want to use the built-in DescriptionAttribute, which will make the code simpler: public static class EnumExtensions { public static string ToDisplayName(this Enum value) { Type type = value.GetType(); MemberInfo[] memInfo =...
23 Sep 2019 by Richard Deeming
To add to Bill's answer, there are a couple of problems with your original code. var type = value.GetType(); var attributes = type.GetTypeInfo().GetCustomAttributes(...); You're looking for attributes on the enum type itself, rather than attributes on the enum member. So: [Enum("...")]...
4 Dec 2020 by Richard MacCutchan
Just about everything is wrong with your code. You are trying to instantiate an abstract class. You are trying to create an instance by passing a class name to a parameterless constructor. You are using the same names for a class, and an...
20 Jan 2021 by Christian Graus
Once you add a datagrid, you can label the columns anyway you want and it's possible to foreach over an enum foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit))) { }
11 Jul 2011 by DavidSilvey
Recently (weeks or months ago)there was an article that talked about adding additional properties to ENUMs. It discussed the fact that in C++ enum was a class and so could be extended. I bookmarked the article because it directly related to a project I was working on. Unfortunately I can no...
20 Oct 2011 by OriginalGriff
This is a bit of a bodge, but it works...Menu items can have shortcut keys, which are effective over the whole of the application. These keys can be changed by setting the ShortcutKeys property.Interestingly, they work even if the menu item, or branch, or even the whole menu system is...
20 Oct 2011 by shoorrock
But how do you convert the accelerator to a user friendly string? if you go to the accelerator property of a toolstrip menu item and try to set an accelerator to say Control + ?, you set Control + Shift + OEMQuestion, the shortcut will show Control + OEMQuestion.There has to be a way to...
20 Oct 2011 by ARBebopKid
The Question Mark is named System.Windows.Forms.Keys.OemQuestionEvery Key in this Class is given an alphanumeric name. I suggest you use if or switch to determine what character is pressed to get that symbol.ORYou may just be talking about setting the ShortcutKeyDisplayString...
20 Oct 2011 by Sergey Alexandrovich Kryukov
Right, the event KeyPress won't help you. You need to work with KeyDown. All you need is the key dictionary. Use System.Collections.Generic.Dictionary. For a value, use some appropriate delegate type. For a key, use a structure if two members: KeyCode and KeyModifiers, such as it is done here:...
20 Oct 2011 by BillWoodruff
+5 Good question !"I need to figure out a way to display the stored keys enum. I've looked high and low for a solution, but having users see commands such as Control + oemkey1 is really ridiculous."I'd like to ask you what exactly you mean here when you say "users see commands:" does...
20 Feb 2012 by Saeid.Babaei86
Hi . how i can Order enum members by their values ?for example i have this enum : public static enum ePersianNumbersliteral { Zero = "\u0660", One = "\u0661", Two = "\u0662", Three = "\u0663", Four = "\u0664", ...
20 Feb 2012 by Abhinav S
This article sorts an enum - Fill Combobox With Sorted Enum Without Code[^].
20 Feb 2012 by Andreas Gieriet
Try this:public enum ePersianNumbersliteral{ Zero = '\u0660', One = '\u0661', Two = '\u0662', Three = '\u0663', Four = '\u0664', Five = '\u0665', Six = '\u0666', Seven = '\u0667', Eight = '\u0668', Nine = '\u0669'}public static...
20 Feb 2012 by Andreas Gieriet
If you *really* want intellisense to list the enums in a value sequence, that value has to be visible in the name as well so that intellisense sorts them properly by sorting the values alphabetically. E.g.public enum ePersianNumbersliteral{ E0_Zero = '\u0660', E1_One =...
5 Jun 2012 by NeonMika
So the problem is the following:I have a Dictionary and I want to access this Dicitionary from XAML.FormatEnum has the types Small, Medium and Big, and the string contains a URL to a picture.I tried the following code:...
5 Jun 2012 by Steve Maier
You can use a converter to change the enum into whatever you need. I use this in a WP7 app to convert a status enum to an image like a green one for good or a red one for an error.WPF - Bind to Opposite Boolean Value Using a Converter[^]Piping Value Converters in WPF[^]
18 Jun 2012 by tamcntt1985
Hi everyone,Could you guys have a sourcecode or the way to get the list of devices in linux environment.Any answer will be appreciated, thanks in advanced.
18 Jun 2012 by Richard MacCutchan
One of these answers[^] should help you.
6 Jul 2012 by Beula Joyce
Hi,I have list of data which are predefined, I don't want to store all those data in the database as it is and also I don't want to have separate table for those data. So I have used Enumerators and saved only the enumerators values like '1,3,4,5,6' in the database. Now I fetch the record as...
1 Aug 2012 by Hamid Moradi
I need help!Using .net 4.0 and WPF I have a property Grid that is bounded to a class and all its properties. One of the properties of the class is of type enum like:public enum ColorChoices{ [Description("My favorite color - Red")] Red, [Description("My second favorite...
1 Aug 2012 by Kenneth Haugland
Your question has a full demo here:Step by Step WPF Data Binding with Comboboxes[^]
1 Aug 2012 by André Kraak
Have a look at this article: Displaying User Friendly Enum Values in WPF[^]It has a section called Text customization using code attributes.Addition:Another article is Binding and Using Friendly Enums in WPF[^], it is actually mentioned in the first article I listed.
1 Aug 2012 by Sergey Alexandrovich Kryukov
I have a very general article on the problem of human-readable names for .NET enumeration members, with very universal approach. Please read it:Human-readable Enumeration Meta-data[^].—SA
18 Dec 2012 by robert_54
I have a datagridview in one form which has a quantity field. it contains int type of numbers. I want to be able to create a combobox field in another datagridview in another form which will get a range depending on the quantity in the other form.for example the quantity I input in the first...
18 Dec 2012 by Jibesh
You could try setting different data source to the cell than for the grid.like this:DataGridViewComboBoxColumn newColumn = new DataGridViewComboBoxColumn();newColumn.Name = "abc";newColumn.DataSource = new string[] { "a", "b", "c" };dataGridView1.Columns.Add(newColumn);foreach...
6 Feb 2013 by leprechauny
public enum Colour { red, blue, green }public enum Taste { sour, salt, blue }etc.I'm having trouble figuring out how to bind these two enums to one list simultaneously. Would it be solved by using an array?...
6 Feb 2013 by Sergey Alexandrovich Kryukov
Please see my comment to the question.For other ideas, I can suggest two sources. First, look at my past answers collected in one: combobox.selectedvalue shows {} in winform[^].The idea is: you should create a data class which can use both enumeration types and some other data, to put...
19 Jun 2013 by Divakar Raj M
I have defined an enum and tried to retrieve it as followsclass Demo{ enum hello { one=1, two } public static void Main() { Console.WriteLine(hello.one); Console.ReadLine(); }}Now, how do i retrieve the integer...
6 Aug 2013 by wonder-FOOL
Hello all,I am trying to use an enum as a optional parameter. But i get en error saying "identifier expected". Can anyone tell me how to use enum;I have tried the following code;enum attachmentType { filePath , fileString}; public static void SendEmail(attachmentType =...
6 Aug 2013 by Manas Bhardwaj
Should be like this:enum attachmentType { filePath , fileString};public static void SendEmail(attachmentType type = attachmentType.filePath){ // Do stuff}You are missing the parameter name.
13 Aug 2013 by Pheonyx
Yes, don't do it like that (I never managed to get that approach to work0. There is a much better approach you can use which I think is more re-usable. Use the [Description()] Attribute on your enum like this:Public Enum Fruit Oranges ...
24 Aug 2013 by User 1138000
Quote:I don'tget it. The only way to get a result of false is by providing a number...If you mean "providing a number" as in:enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };...var day = (Days)42;...if (Enum.IsDefined(typeof(Days), day)) ...Then I...
18 Nov 2013 by ♥…ЯҠ…♥
Hi Guys,I have declared enum like thisenum monthToVal { JAN=1,FEB,MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }Is it possible to take FEB from enum?string monthName = monthToVal(2) or monthToVal(DateTime.Now.Month) or something like this?Like...
18 Nov 2013 by W Balboos, GHB
Why not do this all the correct way - with a data array?Create a structure for all your desired data, such as:struct YearParts { int monNum; // Month Number 1-12 int monSize; // Days In Month (don't forget to test for leap-year!) string monShort; // Three-char month name ...
2 Mar 2014 by OriginalGriff
There is no automatic way to sort enums into alphabetical order in VS so that:public enum myEnum { aaaa, dddd, eeee, bbbb }becomespublic enum myEnum { aaaa, bbbb, dddd, eeee }If that is what you want, you will have to do it...
2 Mar 2014 by dan!sh
I don't think you are using right object for the job. Order of elements in an Enum should be governed by integer value it holds and not by the text. Image a days of week enum that is displayed alphabetically on screen.I think what you need here is a sorted list or dictionary.
3 Mar 2014 by Maciej Los
There are two different things:1) bind enumeration,2) sort data.Ad 1)Have a look here:How to: Bind to an Enumeration[^]Accessing Enum members in Xaml[^]Ad 2) If enumeration is bind to any control, use its method to sort data.
3 Mar 2014 by King Fisher
i hope its useful for you.refer thisC# sort with examples
5 Apr 2014 by M­­ar­­­­k
Hi... Ive seen some examples in http://docs.oracle.com/[^] that contains enums with some variables inside each enum objects like the example below...public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), ...
5 Apr 2014 by Thomas Daniels
You should try it the other way around: now you do English word = Dutch word, but you should do Dutch word = English word:enum Seizoen { spring, summer, autumn, winter, lente = spring, zomer = summer, herfst = autumn };First, add the English words to the enum and then add the Dutch words to it.
11 Apr 2014 by Naz_Firdouse
have a look at theseEnum to ComboBox binding[^]http://stackoverflow.com/questions/7390303/enum-with-space-property-for-dropdownlist[^]http://www.geospecialling.com/index.php/2013/02/enum-the-simple-c-value-type-we-love-to-complicate/[^]
14 Apr 2014 by Pheonyx
Hi Guys,I hope you are all well and that someone here might be able to shed some light on my issue.I have a database table with the following setup:ID [Bigint]Name [nvarchar(250)]ISOCode [nvarchar(5)]MarketType [tinyint]Using EntityFramework 6 Database first, I have added...
14 Apr 2014 by Dave Kreskowiak
The first question is why are you using "Type"? That is not a good name to use as it is a class name that is used by .NET and is going to lead to confusion in the code.I think your Type should become MarketType, and could also be the name of your Enum. public enum MarketType { ...
15 Jun 2014 by Gold$Coin
Hi all,i would like to use GreaterThanorEqual and Equal to and LessThanorEqual in ENUM which mean my ENUM will be like belowenum StringCompare { strA_is_less_than_strB = 1 }shall i use something like or is there is any other way to...
15 Jun 2014 by Prasad Avunoori
You may use like the following: enum StringCompare { strA_is_less_than_strB = -1, strAequals_strB , strA_is_greater_than_strB }
15 Jun 2014 by Bernhard Hiller
You try it in a strange way. Look at the functions Enum.IsDefined or Enum.GetValues. Unfortunately, there is no Enum.TryParse function, but you could write an Extension method for that.
17 Jul 2014 by jgauffin
How to safely convert enums
5 Aug 2014 by Santiago Fabian
I want to know if its possible to create a CRL stored procedure in C# with a parameter of enum type?If so, what value should I pass to this parameter once I execute it in sql server management studio?My c# code would be something like this to give you an idea:enum Processtype { ...
5 Aug 2014 by Sergey Alexandrovich Kryukov
Unfortunately, "stored procedure" is never CLR. By definition, this is a SQL procedure. The code being executed in CLR can only create the code of the SP, trigger its execution, pick up the results of its execution from the SQL server.And SQL does not have general enumeration types. (Some...
29 Aug 2014 by Suvabrata Roy
Hi,I found the cause.Its very funny...In your case public enum Weekdays{ Sunday, Monday=Sunday, Tuesday, Wednesday=Sunday, Thursday, Friday, Saturday }Few rule :1. If you don't set any value to enum it will...
7 Sep 2014 by _Asif_
Try Enum.TryParse[^], should do what you want.
22 Oct 2014 by SirLearnAlot
I solved the problem. I changed selectedValue method to selectedIndex, then I changed each option to correspond with index values from 0 - 2.Provided working code, thanks to all who tried to help!private void Tracking_Button_Click(object sender, RoutedEventArgs e) { ...
15 Jan 2015 by Member 11377096
I am exploring TDD and state transition testing. I have a hard time getting my head around how this test can be written before the code. In an attempt to understand I started to write the actual method first and then the test.But I want to do it as TDD not reverse engineering.Could someone...
15 Jan 2015 by George Swan
I’m not an expert on this, so I have posted what follows as a self -help and learning exercise for the two of us. This is my take on the problem.As it stands, your changeMode method is dependent upon three other classes, theDate, theTime and MessageBox. It has a dual purpose, to return a...
3 Nov 2015 by schlumpfger
Hi,How can I order the enum values in propertygrid by descripion?Public Class myObject Public Enum eFolderOrder l= 0 m= 1 n= 2 End Enum ...
3 Nov 2015 by Maciej Los
In addition to solution 1 by Richard Deeming[^], i'd recommend to read this: Adding Descriptions to your Enumerations[^]. Even if this article uses c# code, you're able to convert it to vb.net.
3 Jul 2016 by 7045Jeegnesh
1 ) it'sEnum With descriptionPublic Enum ActionDrug_list Drug_withdrawn = 1 Drug_reduced = 2 Drug_increased = 3 Dose_not_changed...
24 Aug 2016 by Dev O'Connor
Hi,i am not sure if this is at all possible, and i have tried myself but cannot seem to get anywhere with it:i have several sub classes that perform a bunch of sql statements and hold values in sub classes, one downside to this is that i have to have to setup properties under each class...
2 Dec 2017 by ilostmyid2
A field in database at server-side is defined as ENUM. A row of database is returned via a web service including the field. I have to define a type for the returned result. In PHP, I use NuSoap for this purpose. I use addComplexType function. How this function should be called? With what...
2 Dec 2017 by ilostmyid2
Here is an example of the method for creating a new type of enum: $server->wsdl->addSimpleType('ServerStatus', 'xsd:string', 'SimpleType', 'struct', array(‎ 'Off', 'Stopped', 'Running' )); Then, in Server structure the following line defines the server's...
16 Apr 2018 by Member 10337327
Hello I am new to Sharepoint. I have added an enum property to add a dropdown with static list items like this:
25 Apr 2018 by C. David Johnson
I'm working with a 3rd party file so I did not design the structure, and I'm stuck with it. For some reason all my enums are selecting the first value in the list instead of the correct one First here is my deserialization code using (var stream = new FileStream(filetoimport,...