Search Results

Search found 1234 results on 50 pages for 'enum'.

Page 3/50 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Convert Enum to String

    - by Eric Weilnau
    Which is the preferred way to convert an Enum to a String in .NET 3.5? Enum.GetName Enum.Format toString Why should I prefer one of these over the others? Does one perform better? Justification for Accepted Answer Based on the forum post in panesofglass answer, it appears that Microsoft indirectly endorses the following method of converting an enum value to a string. Do not convert an enum value to a string using built-in enum methods. ... This will cause problems when Dotfuscating. You should not use enum.ToString(), enum.GetNames(), enum.GetName(), enum.Format() or enum.Parse() to convert an enum to a string. Instead, use a switch statement, and also internationalize the names if necessary.

    Read the article

  • Trying to get the associated value from an Enum at runtime in Java

    - by devoured elysium
    I want to accomplish something like the following (my interest is in the toInt() method). Is there any native way to accomplish this? If not, how can I get the integer associated with an enum value (like in C#) ? enum Rate { VeryBad(1), Bad(2), Average(3), Good(4), Excellent(5); private int rate; private Rate(int rate) { this.rate = rate; } public int toInt() { return rate; } } Thanks

    Read the article

  • Enum types, FlagAttribute & Zero value

    - by nmgomes
    We all know about Enums types and use them every single day. What is not that often used is to decorate the Enum type with the FlagsAttribute. When an Enum type has the FlagsAttribute we can assign multiple values to it and thus combine multiple information into a single enum. The enum values should be a power of two so that a bit set is achieved. Here is a typical Enum type: public enum OperationMode { /// <summary> /// No operation mode /// </summary> None = 0, /// <summary> /// Standard operation mode /// </summary> Standard = 1, /// <summary> /// Accept bubble requests mode /// </summary> Parent = 2 } In such scenario no values combination are possible. In the following scenario a default operation mode exists and combination is used: [Flags] public enum OperationMode { /// <summary> /// Asynchronous operation mode /// </summary> Async = 0, /// <summary> /// Synchronous operation mode /// </summary> Sync = 1, /// <summary> /// Accept bubble requests mode /// </summary> Parent = 2 } Now, it’s possible to do statements like: [DefaultValue(OperationMode.Async)] [TypeConverter(typeof(EnumConverter))] public OperationMode Mode { get; set; } /// <summary> /// Gets a value indicating whether this instance supports request from childrens. /// </summary> public bool IsParent { get { return (this.Mode & OperationMode.Parent) == OperationMode.Parent; } } or switch (this.Mode) { case OperationMode.Sync | OperationMode.Parent: Console.WriteLine("Sync,Parent"); break;[…]  But there is something that you should never forget: Zero is the absorber element for the bitwise AND operation. So, checking for OperationMode.Async (the Zero value) mode just like the OperationMode.Parent mode makes no sense since it will always be true: (this.Mode & 0x0) == 0x0 Instead, inverse logic should be used: OperationMode.Async = !OperationMode.Sync public bool IsAsync { get { return (this.Mode & ContentManagerOperationMode.Sync) != ContentManagerOperationMode.Sync; } } or public bool IsAsync { get { return (int)this.Mode == 0; } } Final Note: Benefits Allow multiple values combination The above samples snippets were taken from an ASP.NET control and enabled the following markup usage: <my:Control runat="server" Mode="Sync,Parent"> Drawback Zero value is the absorber element for the bitwise AND operation Be very carefully when evaluating the Zero value, either evaluate the enum value as an integer or use inverse logic.

    Read the article

  • Databinding a .Net WinForms ComboBox to an Enum

    - by Tim Huffam
    This is quite simple... Define the enum eg: public enum MyEnum{ ItemOne, ItemTwo, } Within the form set the datasource of the combobox to the values of the enum eg: myCombo.DataSource = System.Enum.GetValues(typeof(MyEnum)); To have the combo auto select a value based on a bound object, set the databinding of the combo eg: class MyObject{ private MyEnum myEnumProperty; public MyEnum MyEnumProperty{get {return myEnumProperty;}} } MyObject myObj = new MyObject(); myCombo.DataBindings.Add(new Binding("SelectedIndex", myObject, "MyEnumProperty");

    Read the article

  • How to return an enum ID instead of the enum text in WebAPI

    - by Rodney
    I am using the WebAPI with .NET 4.5. I have a enum called DareStatus which is a list of statuses and their corresponding integer ID's. To minimize bandwidth traffic I want to send the int values of the enums, not the full text as it is currently doing. (I have control over the client so I can map it on the clientside). The strange thing is that in my RTFM-ing everyone seems to have the opposite issue! http://www.ftter.com/desktopmodules/framework/api/dare/getalldares public enum DareStatus : int { All = 0, Accepted = 2, Pending = 1, Declined = 3, Cancelled = 4, Failed = 5, Won = 6 } public IEnumerable<DareInfo> GetDares() { IEnumerable<DareInfo> dareInfos; using (IDataContext ctx = DataContext.Instance()) { var rep = ctx.GetRepository<DareInfo>(); dareInfos = rep.Get(); } return dareInfos; }

    Read the article

  • XCode enum woes

    - by Raconteur
    Hi gang, I thought I had this sorted, but I am still missing something. Very simply, I have a Settings class that hold a DAO (sitting on a plist). I want to have a couple of enums for the settings for convenience and readability, such as GamePlayType and DifficultyLevel. Right now I am defining them in the Settings.h file above the @interface line as such: typedef enum { EASY, NORMAL, HARD } DifficultyLevel; and typedef enum { SET_NUMBER_OF_MOVES, TO_COMPLETION } GamePlayType; If I access them from within the Settings class like: - (int)gridSizeForLOD { switch ([self difficultyLevel]) { case EASY: return GRID_SIZE_EASY; case NORMAL: return GRID_SIZE_NORMAL; case HARD: return GRID_SIZE_HARD; default: return GRID_SIZE_NORMAL; } } everything is fine. But, if I try to access them outside of the Settings class, let's say in my main view controller class, like this: if (([settings gameType] == SET_NUMBER_OF_MOVES) && (numMoves == [settings numMovesForLOD])) { [self showLoseScreen]; } I get errors (like EXC_BAD_ACCESS) or the condition always fails. Am I doing something incorrectly? Also, I should point out that I have this code for the call to gameType (which lives in the Settings class): - (GamePlayType)gameType { return [dao gameType]; } and the DAO implements gameType like this: - (int)gameType { return (settingsContent != nil) ? [[settingsContent objectForKey:@"Game Type"] intValue] : 0; } I know I have the DAO returning an int instead of a GamePlayType, but A) the problem I am describing arose there when I tried to use the "proper" data type, and B) I did not think it would matter since the enum is just a bunch of named ints, right? Any help, greatly appreciated. I really want to understand this thoroughly, and something is eluding me... Cheers, Chris

    Read the article

  • Zend_Db Enum Values [Closed]

    - by scopus
    I find this solution $metadata = $result->getTable()->info('metadata'); echo $metadata['Continent']['DATA_TYPE']; Hi, I want to get enum values in Zend_Db. My Code: $select = $this->select(); $result = $select->fetchAll(); print_r($result->getTable()); Output: Example Object ( [_name] => country [query] => Zend_Db_Table_Select Object ( [_info:protected] => Array ( [schema] => [name] => country [cols] => Array ( [0] => Code [1] => Continent ) [primary] => Array ( [1] => Code ) [metadata] => Array ( [Continent] => Array ( [SCHEMA_NAME] => [TABLE_NAME] => country [COLUMN_NAME] => Continent [COLUMN_POSITION] => 3 [DATA_TYPE] => enum('Asia','Europe','North America','Africa','Oceania','Antarctica','South America') [DEFAULT] => Asia [NULLABLE] => [LENGTH] => [SCALE] => [PRECISION] => [UNSIGNED] => [PRIMARY] => [PRIMARY_POSITION] => [IDENTITY] => ) I see enum values in data_type but i don't get this values. How can get data_type?

    Read the article

  • Enum exeeding the 65535 bytes limit of static initializer... what's best to do?

    - by Daniel Bleisteiner
    I've started a rather large Enum of so called Descriptors that I've wanted to use as a reference list in my model. But now I've come across a compiler/VM limit the first time and so I'm looking for the best solution to handle this. Here is my error : The code for the static initializer is exceeding the 65535 bytes limit It is clear where this comes from - my Enum simply has far to much elements. But I need those elements - there is no way to reduce that set. Initialy I've planed to use a single Enum because I want to make sure that all elements within the Enum are unique. It is used in a Hibernate persistence context where the reference to the Enum is stored as String value in the database. So this must be unique! The content of my Enum can be devided into several groups of elements belonging together. But splitting the Enum would remove the unique safety I get during compile time. Or can this be achieved with multiple Enums in some way? My only current idea is to define some Interface called Descriptor and code several Enums implementing it. This way I hope to be able to use the Hibernate Enum mapping as if it were a single Enum. But I'm not even sure if this will work. And I loose unique safety. Any ideas how to handle that case?

    Read the article

  • How to query flags stored as enum in NHibernate

    - by SztupY
    How to do either a HQL or a Criteria search (the latter is preferred) involving an enum that is used as flags. In other words, I have a persisted enum property that stores some kind of flags. I want to query all the records that have one of these flags set. Using Eq won't work of course because that will only be true, if that is the only flag set. Solving this using the Criteria API would be the best, but if this is only doable using HQL that is good too.

    Read the article

  • C++ pass enum as parameter

    - by Spencer
    If I have a simple class like this one for a card: class Card { public: enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }; Card(Suit suit); }; and I then want to create an instance of a card in another file how do I pass the enum? #include "Card.h" using namespace std; int main () { Suit suit = Card.CLUBS; Card card(suit); return 0; } error: 'Suit' was not declared in this scope I know this works: #include "Card.h" using namespace std; int main () { Card card(Card.CLUBS); return 0; } but how do I create a variable of type Suit in another file? Thanks, Spencer

    Read the article

  • Best way to store enum values in database - String or Int

    - by inutan
    Hello there, I have a number of enums in my application which are used as property type in some classes. What is the best way to store these values in database, as String or Int? FYI, I will also be mapping these attribute types using fluent Nhibernate. Sample code: public enum ReportOutputFormat { DOCX, PDF, HTML } public enum ReportOutputMethod { Save, Email, SaveAndEmail } public class ReportRequest { public Int32 TemplateId { get { return templateId; } set { templateId = value; } } public ReportOutputFormat OutputFormat { get { return outputFormat; } set { outputFormat = value; } } public ReportOutputMethod OutputMethod { get { return outputMethod; } set { outputMethod = value; } } }

    Read the article

  • Boost::Container::Vector with Enum Template Argument - Not Legal Base Class

    - by CuppM
    Hi, I'm using Visual Studio 2008 with the Boost v1.42.0 library. If I use an enum as the template argument, I get a compile error when adding a value using push_back(). The compiler error is: 'T': is not a legal base class and the location of the error is move.hpp line 79. #include <boost/interprocess/containers/vector.hpp> class Test { public: enum Types { Unknown = 0, First = 1, Second = 2, Third = 3 }; typedef boost::container::vector<Types> TypesVector; }; int main() { Test::TypesVector o; o.push_back(Test::First); return 0; } If I use a std::vector instead it works. And if I resize the Boost version first and then set the values using the [] operator it also works. Is there some way to make this work using push_back()?

    Read the article

  • Enum : get the keys list

    - by Damien MATHIEU
    Hello, I'm not a java developer. But I'm currently taking a look at Android applications development so I'm doing a bit of nostalgy, doing some java again after not touching it for three years. I'm looking forward using the "google-api-translate-java" library. In which there is a Language class. It's an enum allowing to provide the language name and to get it's value for Google Translate. I can easily get all the values with : for (Language l : values()) { // Here I loop on one value } But what I'd want to get is a list of all the keys names (FRENCH, ENGLISH, ...). Is there something like a "keys()" method that'd allow me to loop through all the enum's keys ?

    Read the article

  • Java enum pairs / "subenum" or what exactly?

    - by vemalsar
    I have an RPG-style Item class and I stored the type of the item in enum (itemType.sword). I want to store subtype too (itemSubtype.long), but I want to express the relation between two data type (sword can be long, short etc. but shield can't be long or short, only round, tower etc). I know this is wrong source code but similar what I want: enum type { sword; } //not valid code! enum swordSubtype extends type.sword { short, long } Question: How can I define this connection between two data type (or more exactly: two value of the data types), what is the most simple and standard way? Array-like data with all valid (itemType,itemSubtype) enum pairs or (itemType,itemSubtype[]) so more subtype for one type, it would be the best. OK but how can I construct this simplest way? Special enum with "subenum" set or second level enum or anything else if it does exists 2 dimensional "canBePairs" array, itemType and itemSubtype dimensions with all type and subtype and boolean elements, "true" means itemType (first dimension) and itemSubtype (second dimension) are okay, "false" means not okay Other better idea Thank you very much!

    Read the article

  • Extract all related class type aliasing and enum into one file or not

    - by Chen OT
    I have many models in my project, and some other classes just need the class declaration and pointer type aliasing. It does not need to know the class definition, so I don't want to include the model header file. I extract all the model's declaration into one file to let every classes reference one file. model_forward.h class Cat; typedef std::shared_ptr<Cat> CatPointerType; typedef std::shared_ptr<const Cat> CatConstPointerType; class Dog; typedef std::shared_ptr<Dog> DogPointerType; typedef std::shared_ptr<const Dog> DogConstPointerType; class Fish; typedef std::shared_ptr<Fish> FishPointerType; typedef std::shared_ptr<const Fish> FishConstPointerType; enum CatType{RED_CAT, YELLOW_CAT, GREEN_CAT, PURPLE_CAT} enum DogType{HATE_CAT_DOG, HUSKY, GOLDEN_RETRIEVER} enum FishType{SHARK, OCTOPUS, SALMON} Is it acceptable practice? Should I make every unit, which needs a class declaration, depends on one file? Does it cause high coupling? Or I should put these pointer type aliasing and enum definition inside the class back? cat.h class Cat { typedef std::shared_ptr<Cat> PointerType; typedef std::shared_ptr<const Cat> ConstPointerType; enum Type{RED_CAT, YELLOW_CAT, GREEN_CAT, PURPLE_CAT} ... }; dog.h class Dog { typedef std::shared_ptr<Dog> PointerType; typedef std::shared_ptr<const Dog> ConstPointerType; enum Type{HATE_CAT_DOG, HUSKY, GOLDEN_RETRIEVER} ... } fish.h class Fish { ... }; Any suggestion will be helpful.

    Read the article

  • " not all code paths return a value" when return enum type

    - by netmajor
    I have enum list and method and i get error: " not all code paths return a value" Some idea whats wrong in my method ? I am sure I always return STANY type :/ Thanks for help :) private enum STANY { PATROL, CHAT, EAT, SEARCH, DIE }; private STANY giveState(int id, List<Ludek> gracze, List<int> plansza) { // Sprawdz czy gracz stoi na polu z jedzeniem i nie ma 2000 jednostek jedzenia bool onTheFood = false; onTheFood = CzyPoleZjedzeniem(id, gracze, plansza, onTheFood); if (onTheFood && (gracze[id].IloscJedzenia < startFood / 2)) return STANY.EAT; // Sprawdz czy gracz nie stoi na polu z innym graczem bool allKnowledge = true; allKnowledge = CzyPoleZInnymGraczem(id, gracze, allKnowledge); if (!allKnowledge) return STANY.CHAT; // Jesli ma ponad i rowna ilosc jedzenia patroluj if (gracze[id].IloscJedzenia >= startFood / 2) return STANY.PATROL; // Jesli ma mniej niz polowe jedzenia szukaj jedzenia if (gracze[id].IloscJedzenia > 0 && gracze[id].IloscJedzenia < startFood / 2) return STANY.SEARCH; // Jesli nie ma jedzenia umieraj if (gracze[id].IloscJedzenia <= 0) return STANY.DIE; }

    Read the article

  • g++ C++0x enum class Compiler Warnings

    - by Travis G
    I've been refactoring my horrible mess of C++ type-safe psuedo-enums to the new C++0x type-safe enums because they're way more readable. Anyway, I use them in exported classes, so I explicitly mark them to be exported: enum class __attribute__((visibility("default"))) MyEnum : unsigned int { One = 1, Two = 2 }; Compiling this with g++ yields the following warning: type attributes ignored after type is already defined This seems very strange, since, as far as I know, that warning is meant to prevent actual mistakes like: class __attribute__((visibility("default"))) MyClass { }; class __attribute__((visibility("hidden"))) MyClass; Of course, I'm clearly not doing that, since I have only marked the visibility attributes at the definition of the enum class and I'm not re-defining or declaring it anywhere else (I can duplicate this error with a single file). Ultimately, I can't make this bit of code actually cause a problem, save for the fact that, if I change a value and re-compile the consumer without re-compiling the shared library, the consumer passes the new values and the shared library has no idea what to do with them (although I wouldn't expect that to work in the first place). Am I being way too pedantic? Can this be safely ignored? I suspect so, but at the same time, having this error prevents me from compiling with Werror, which makes me uncomfortable. I would really like to see this problem go away.

    Read the article

  • SFINAE failing with enum template parameter

    - by zeroes00
    Can someone explain the following behaviour (I'm using Visual Studio 2010). header: #pragma once #include <boost\utility\enable_if.hpp> using boost::enable_if_c; enum WeekDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}; template<WeekDay DAY> typename enable_if_c< DAY==SUNDAY, bool >::type goToWork() {return false;} template<WeekDay DAY> typename enable_if_c< DAY!=SUNDAY, bool >::type goToWork() {return true;} source: bool b = goToWork<MONDAY>(); compiler this gives error C2770: invalid explicit template argument(s) for 'enable_if_c<DAY!=6,bool>::type goToWork(void)' and error C2770: invalid explicit template argument(s) for 'enable_if_c<DAY==6,bool>::type goToWork(void)' But if I change the function template parameter from the enum type WeekDay to int, it compiles fine: template<int DAY> typename enable_if_c< DAY==SUNDAY, bool >::type goToWork() {return false;} template<int DAY> typename enable_if_c< DAY!=SUNDAY, bool >::type goToWork() {return true;} Also the normal function template specialization works fine, no surprises there: template<WeekDay DAY> bool goToWork() {return true;} template<> bool goToWork<SUNDAY>() {return false;} To make things even weirder, if I change the source file to use any other WeekDay than MONDAY or TUESDAY, i.e. bool b = goToWork<THURSDAY>(); the error changes to this: error C2440: 'specialization' : cannot convert from 'int' to 'const WeekDay' Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast)

    Read the article

  • overriding enumeration base type using pragma or code change

    - by vprajan
    Problem: I am using a big C/C++ code base which works on gcc & visual studio compilers where enum base type is by default 32-bit(integer type). This code also has lots of inline + embedded assembly which treats enum as integer type and enum data is used as 32-bit flags in many cases. When compiled this code with realview ARM RVCT 2.2 compiler, we started getting many issues since realview compiler decides enum base type automatically based on the value an enum is set to. http://www.keil.com/support/man/docs/armccref/armccref_Babjddhe.htm For example, Consider the below enum, enum Scale { TimesOne, //0 TimesTwo, //1 TimesFour, //2 TimesEight, //3 }; This enum is used as a 32-bit flag. but compiler optimizes it to unsigned char type for this enum. Using --enum_is_int compiler option is not a good solution for our case, since it converts all the enum's to 32-bit which will break interaction with any external code compiled without --enum_is_int. This is warning i found in RVCT compilers & Library guide, The --enum_is_int option is not recommended for general use and is not required for ISO-compatible source. Code compiled with this option is not compliant with the ABI for the ARM Architecture (base standard) [BSABI], and incorrect use might result in a failure at runtime. This option is not supported by the C++ libraries. Question How to convert all enum's base type (by hand-coded changes) to use 32-bit without affecting value ordering? enum Scale { TimesOne=0x00000000, TimesTwo, // 0x00000001 TimesFour, // 0x00000002 TimesEight, //0x00000003 }; I tried the above change. But compiler optimizes this also for our bad luck. :( There is some syntax in .NET like enum Scale: int Is this a ISO C++ standard and ARM compiler lacks it? There is no #pragma to control this enum in ARM RVCT 2.2 compiler. Is there any hidden pragma available ?

    Read the article

  • Best method to store Enum in Database

    - by LnDCobra
    What is the best method of storing an Enum in a Database using C# And Visual Studio and MySQL Data Connector. I am going to be creating a new project with over 100 Enums, and majority of them will have to be stored in the database. Creating converters for each one would be a long winded process therefore I'm wondering if visual studio or someone has any methods for this that I haven't heard off.

    Read the article

  • Wpf ListViewItem Background binding to enum

    - by Christian
    Hi Guys I´ve got a ListView which is bound to the ObservableCollection mPersonList. The Class Person got an enum Sex. What i want to do is to set the background of the ListViewItem to green if the person is male and to red if the person is female. Thanks for the answers!

    Read the article

  • Mapping enum types with Hibernate Annotations

    - by Thiago
    Hi there, I have an enum type on my Java model which I'd like to map to a table on the database. I'm working with Hibernate Annotations and I don't know how to do that. Since the answers I search were rather old, I wonder which way is the best? Thanks in advance

    Read the article

  • How to refer to enum constants in c# xml docs

    - by Bruno Martinez
    I want to document the default value of an enum typed field: /// <summary> /// The default value is <see cref="Orientation.Horizontal" />. /// </summary> public Orientation BoxOrientation; The compiler warns that it couldn't resolve the reference. Prefixing F: or M: silences the compiler, but E: also does, so I'm unsure what prefix is correct.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >