Search Results

Search found 414 results on 17 pages for 'enums'.

Page 8/17 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Constraining enum value in method parameter

    - by fearofawhackplanet
    enum Fruit { Banana, Orange, Strawberry ... ... // etc, very long enum } PeelFruit(Fruit.Orange); PeelFruit(Fruit.Banana); PeelFruit(Fruit.Strawberry); // huh? can't peel strawberries! Sorry for the lame example, but hopefully you get the idea. Is there a way to constrain the enum values that PeelFruit will accept? Obvisouly I could check them in the method with a switch or something, but it would be cool if there was a way to do it that is a) a bit more compact, and b) would cause a compile time error, not a run time error. [Fruit = Orange,Bannana] void PeelFruit(Fruit fruit) { ... }

    Read the article

  • Scala - Enumeration vs. Case-Classes

    - by tzofia
    I've created akka actor called LogActor. The LogActors's receive method handling messages from other actors and logging them to the specified log level. I can distinguish between the different levels in 2 ways. The first one: import LogLevel._ object LogLevel extends Enumeration { type LogLevel = Value val Error, Warning, Info, Debug = Value } case class LogMessage(level : LogLevel, msg : String) The second: (EDIT) abstract class LogMessage(msg : String) case class LogMessageError(msg : String) extends LogMessage(msg) case class LogMessageWarning(msg : String) extends LogMessage(msg) case class LogMessageInfo(msg : String) extends LogMessage(msg) case class LogMessageDebug(msg : String) extends LogMessage(msg) Which way is more efficient? does it take less time to match case class or to match enum value? (I read this question but there isn't any answer referring to the runtime issue)

    Read the article

  • How can I store an inventory-like list of numbers?

    - by Rachel
    I've got a list of number that I need to keep track of. The numbers are loosely related, but represent distinctly different items. I'd like to keep a list of the numbers but be able to refer to them by name so that I can call them and use them where needed easily. Kind of like an inventory listing, where the numbers all refer to a part ID and I'd like to call them idPart1, idPart2, idPart3 so their purpose is easily identifiable when they are used. What would be the best way to do this? 1)Define a structure. Say, PartIds. A number of int members will be included, part1, part2 etc. To use, an instance of the structure will be created, values assigned to the members, and the numbers will be used by saying struct.member as needed. 2)Define an enumeration. Use part1, part2 as the enum literals. Store the actual values in a vector or list, each one at the index corresponding to the value of the number's name within the enum. Use the enum literals to retrieve the values, list[enumLit]. 3)Something completely different There's nothing else I need to do with the numbers - just look them up every once in a while. Since there's no processing, I kind of think a new class for them is overkill, but I'm willing to be convinced otherwise. Any suggestions?

    Read the article

  • Fluent Nhibernate expression to select on flagged enum

    - by mbalkema
    I have a domain entity that has a flagged enum as a property. The flagged enum is the target audience for the these entities. The user then has a flagged enum value of the entities they should see. I am trying to figure out the correct expression to select entities that meet the target audience for the user. public class File { public virtual TargetAudience TargetAudience { get; set; } } [Flags] public enum TargetAudience { Audience1 = 1, Audience2 = 2, Audience3 = 4, Audience4 = 8 } Expression: (This works when performed on a IList<File>, but doesn't work on a query to the database.) public Expression<Func<File, bool>> Expression { get { return ((x.TargetAudience & UserTargetedAudience) > 0); } } Any suggestions would be helpful.

    Read the article

  • A ResetBindings on a BindingSource of a Grid also resets ComboBox

    - by Tetsuo
    Hi there, I have a DataGridView with a BindingSource of products. This products have an enum (Producer). For the most text fields (to edit the product) below the DataGridView I have a method RefreshProduct which does a ResetBindings in the end to refresh the DataGridView. There is a ComboBox (cboProducer), too. If I run over the _orderBs.ResetBindings(false) it will reset my cboProducer outside the DataGridView, too. Could you please help me to avoid this? Here follows some code; maybe it is then better to understand. public partial class SelectProducts : UserControl { private AutoCompleteStringCollection _productCollection; private ProductBL _productBL; private OrderBL _orderBL; private SortableBindingList<ProductBE> _listProducts; private ProductBE _selectedProduct; private OrderBE _order; BindingSource _orderBs = new BindingSource(); public SelectProducts() { InitializeComponent(); if (_productBL == null) _productBL = new ProductBL(); if (_orderBL == null) _orderBL = new OrderBL(); if (_productCollection == null) _productCollection = new AutoCompleteStringCollection(); if (_order == null) _order = new OrderBE(); if (_listProducts == null) { _listProducts = _order.ProductList; _orderBs.DataSource = _order; grdOrder.DataSource = _orderBs; grdOrder.DataMember = "ProductList"; } } private void cmdGetProduct_Click(object sender, EventArgs e) { ProductBE product = _productBL.Load(txtProductNumber.Text); _listProducts.Add(product); _orderBs.ResetBindings(false); } private void grdOrder_SelectionChanged(object sender, EventArgs e) { if (grdOrder.SelectedRows.Count > 0) { _selectedProduct = (ProductBE)((DataGridView)(sender)).CurrentRow.DataBoundItem; if (_selectedProduct != null) { txtArticleNumber.Text = _selectedProduct.Article; txtPrice.Text = _selectedProduct.Price.ToString("C"); txtProducerNew.Text = _selectedProduct.ProducerText; cboProducer.DataSource = Enum.GetValues(typeof(Producer)); cboProducer.SelectedItem = _selectedProduct.Producer; } } } private void txtProducerNew_Leave(object sender, EventArgs e) { string property = CommonMethods.GetPropertyName(() => new ProductBE().ProducerText); RefreshProduct(((TextBoxBase)sender).Text, property); } private void RefreshProduct(object value, string property) { if (_selectedProduct != null) { double valueOfDouble; if (double.TryParse(value.ToString(), out valueOfDouble)) { value = valueOfDouble; } Type type = _selectedProduct.GetType(); PropertyInfo info = type.GetProperty(property); if (info.PropertyType.BaseType == typeof(Enum)) { value = Enum.Parse(info.PropertyType, value.ToString()); } try { Convert.ChangeType(value, info.PropertyType, new CultureInfo("de-DE")); info.SetValue(_selectedProduct, value, null); } catch (Exception ex) { throw new WrongFormatException("\"" + value.ToString() + "\" is not a valid value.", ex); } var produktFromList = _listProducts.Single(p => p.Position == _selectedProduct.Position); info.SetValue(produktFromList, value, null); _orderBs.ResetBindings(false); } } private void cboProducer_SelectedIndexChanged(object sender, EventArgs e) { var selectedIndex = ((ComboBox)(sender)).SelectedIndex; switch ((Producer)selectedIndex) { case Producer.ABC: txtProducerNew.Text = Constants.ABC; break; case Producer.DEF: txtProducerNew.Text = Constants.DEF; break; case Producer.GHI: txtProducerNew.Text = Constants.GHI; break; case Producer.Another: txtProducerNew.Text = String.Empty; break; default: break; } string property = CommonMethods.GetPropertyName(() => new ProductBE().Producer); RefreshProduct(selectedIndex, property); } }

    Read the article

  • mysql enum performance: is enum slower than INT

    - by JP19
    Hi, Is it better to have a field status enum('active', 'hidden', 'deleted') OR status tinyint(3) with a lookup table. Assume that status can take only one value at a time. In particular, I am interested in knowing, are operations on enum significantly slower than or as fast as operations on int ? There is a related question on SO Mysql: enum confusion but i) It does not discuss performance at all ii) There is very little explanation on WHY one approach is better than the other. regards, JP

    Read the article

  • Is it possible in .NET 3.5 to specify an enum type?

    - by RoboShop
    I have a enumerator which map to a bunch of int example enum MyEnum { Open = 1, Closed = 2, Exit = 4 } I find though that when I want to assign this to an integer, I have to cast it first. int myEnumNumber = **(int)** MyEnum.Open; Is it possible to specify the type of an enum so that it is implicit that there is a integer assigned to any value within the enum? That way, I do not need to keep casting it to an int if I want to use it thanks

    Read the article

  • Enum and Dictionary<Enum, Action>

    - by Selcuk
    I hope I can explain my problem in a way that it's clear for everyone. We need your suggestions on this. We have an Enum Type which has more than 15 constants defined. We receive a report from a web service and translate its one column into this Enum type. And based on what we receive from that web service, we run specific functions using Dictionary Why am I asking for ideas? Let's say 3 of these Enum contants meet specific functions in our Dictionary but the rest use the same function. So, is there a way to add them into our Dictionary in a better way rather than adding them one by one? I also want to keep this structure because when it's time, we might have specific functions in the future for the ones that I described as "the rest". To be more clear here's an example what we're trying to do: Enum: public enum Reason{ ReasonA, ReasonB, ReasonC, ReasonD, ReasonE, ReasonF, ReasonG, ReasonH, ReasonI, ReasonJ, ReasonK } Defining our Dictionary: public Dictionary<Reason, Action<CustomClassObj, string>> ReasonHandlers = new Dictionary<Reason, Action<CustomClassObj, string>>{ { Reason.ReasonA, HandleReasonA }, { Reason.ReasonB, HandleReasonB }, { Reason.ReasonC, HandleReasonC }, { Reason.ReasonD, HandleReasonGeneral }, { Reason.ReasonE, HandleReasonGeneral }, { Reason.ReasonF, HandleReasonGeneral }, { Reason.ReasonG, HandleReasonGeneral }, { Reason.ReasonH, HandleReasonGeneral }, { Reason.ReasonI, HandleReasonGeneral }, { Reason.ReasonJ, HandleReasonGeneral }, { Reason.ReasonK, HandleReasonGeneral } }; So basically what I'm asking is, is there a way to add Reason, Function pair more intelligently? Because as you can see after ReasonC, all other reasons use the same function. Thank you for your suggestions.

    Read the article

  • Calling a C function in a DLL with enum parameters from Delphi

    - by dommer
    I have a third-party (Win32) DLL, written in C, that exposes the following interface: DLL_EXPORT typedef enum { DEVICE_PCI = 1, DEVICE_USB = 2 } DeviceType; DLL_EXPORT int DeviceStatus(DeviceType kind); I wish to call it from Delphi. How do I get access to the DeviceType constants in my Delphi code? Or, if I should just use the values 1 and 2 directly, what Delphi type should I use for the "DeviceType kind" parameters? Integer? Word?

    Read the article

  • Using generics in F# to create an EnumArray type

    - by Matthew
    I've created an F# class to represent an array that allocates one element for each value of a specific enum. I'm using an explicit constructor that creates a dictionary from enum values to array indices, and an Item property so that you can write expressions like: let my_array = new EnumArray<EnumType, int> my_array.[EnumType.enum_value] <- 5 However, I'm getting the following obscure compilation error at the line marked with '// FS0670' below. error FS0670: This code is not sufficiently generic. The type variable ^e when ^e : enum<int> and ^e : equality and ^e : (static member op_Explicit : ^e -> int) could not be generalized because it would escape its scope. I'm at a loss - can anyone explain this error? type EnumArray< 'e, 'v when 'e : enum<int> and 'e : equality and ^e : (static member op_Explicit : ^e -> int) > = val enum_to_int : Dictionary<'e, int> val a : 'v array new() as this = { enum_to_int = new Dictionary<'e, int>() a = Array.zeroCreate (Enum.GetValues(typeof<'e>).Length) } then for (e : obj) in Enum.GetValues(typeof<'e>) do this.enum_to_int.Add(e :?> 'e, int(e :?> 'e)) member this.Item with get (idx : 'e) : 'v = this.a.[this.enum_to_int.[idx]] // FS0670 and set (idx : 'e) (c : 'v) = this.a.[this.enum_to_int.[idx]] <- c

    Read the article

  • Mapping enum with fluent nhibernate

    - by Puneet
    I am following the http://wiki.fluentnhibernate.org/Getting%5Fstarted tutorial to create my first NHibernate project with Fluent NHibernate I have 2 tables 1) Account with fields Id AccountHolderName AccountTypeId 2) AccountType with fields Id AccountTypeName Right now the account types can be Savings or Current So the table AccountTypes stores 2 rows 1 - Savings 2 - Current For AccoutType table I have defined enum public enum AccountType { Savings=1, Current=2 } For Account table I define the entity class public class Account { public virtual int Id {get; private set;} public virtual string AccountHolderName {get; set;} public virtual string AccountType {get; set;} } The fluent nhibernate mappings are: public AgencyMap() { Id(o => o.Id); Map(o => o.AccountHolderName); Map(o => o.AccountType); } When I try to run the solution, it gives an exception - InnerException = {"(XmlDocument)(2,4): XML validation error: The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has incomplete content. List of possible elements expected: 'meta, subselect, cache, synchronize, comment, tuplizer, id, composite-id' in namespace 'ur... I guess that is because I have not speciofied any mapping for AccountType. The questions are: How can I use AccountType enum instead of a AccountType class? Maybe I am going on wrong track. Is there a better way to do this? Thanks!

    Read the article

  • Data bind enum properties to grid and display description

    - by TrueWill
    This is a similar question to How to bind a custom Enum description to a DataGrid, but in my case I have multiple properties. public enum ExpectationResult { [Description("-")] NoExpectation, [Description("Passed")] Pass, [Description("FAILED")] Fail } public class TestResult { public string TestDescription { get; set; } public ExpectationResult RequiredExpectationResult { get; set; } public ExpectationResult NonRequiredExpectationResult { get; set; } } I'm binding a BindingList<TestResult> to a WinForms DataGridView (actually a DevExpress.XtraGrid.GridControl, but a generic solution would be more widely applicable). I want the descriptions to appear rather than the enum names. How can I accomplish this? (There are no constraints on the class/enum/attributes; I can change them at will.)

    Read the article

  • C# Event Handlers Using an Enum

    - by Jimbo
    I have a StatusChanged event that is raised by my object when its status changes - however, the application needs to carry out additional actions based on what the new status is. e.g If the new status is Disconnected, then it must update the status bar text and send an email notification. So, I wanted to create an Enum with the possible statuses (Connected, Disconnected, ReceivingData, SendingData etc.) and have that sent with the EventArgs parameter of the event when it is raised (see below) Define the object: class ModemComm { public event CommanderEventHandler ModemCommEvent; public delegate void CommanderEventHandler(object source, ModemCommEventArgs e); public void Connect() { ModemCommEvent(this, new ModemCommEventArgs ModemCommEventArgs.eModemCommEvent.Connected)); } } Define the new EventArgs parameter: public class ModemCommEventArgs : EventArgs{ public enum eModemCommEvent { Idle, Connected, Disconnected, SendingData, ReceivingData } public eModemCommEvent eventType { get; set; } public string eventMessage { get; set; } public ModemCommEventArgs(eModemCommEvent eventType, string eventMessage) { this.eventMessage = eventMessage; this.eventType = eventType; } } I then create a handler for the event in the application: ModemComm comm = new ModemComm(); comm.ModemCommEvent += OnModemCommEvent; and private void OnModemCommEvent(object source, ModemCommEventArgs e) { } The problem is, I get a 'Object reference not set to an instance of an object' error when the object attempts to raise the event. Hoping someone can explain in n00b terms why and how to fix it :)

    Read the article

  • C# Test if an object is an Enum

    - by Aran Mulholland
    I would like to know if 'theObject' is an enum (of any enum type) foreach (var item in Enum.GetValues(theObject.GetType())) { //make sure we have all the enumeration values in the collection if (this.ValuesCollection.Contains(item)) { } else { this.ValuesCollection.Add(item); } Console.WriteLine(item.ToString()); Console.WriteLine(item.GetType().ToString()); }

    Read the article

  • Entity Framework 5 Enum Naming

    - by Tyrel Van Niekerk
    I am using EF 5 with migrations and code first. It all works rather nicely, but there are some issues/questions I would like to resolve. Let's start with a simple example. Lets say I have a User table and a user type table. The user type table is an enum/lookup table in my app. So the user table has a UserTypeId column and a foreign key ref etc to UserType. In my poco, I have a property called UserType which has the enum type. To add the initial values to the UserType table (or add/change values later) and to create the table in the initial migrator etc. I need a UserType table poco to represent the actual table in the database and to use in the map files. I mapped the UserType property in the User poco to UserTypeId in the UserType poco. So now I have a poco for code first/migrations/context mapping etc and I have an enum. Can't have the same name for both, so do I have a poco called UserType and something else for the enum or have the poco for UserType be UserTypeTable or something? More importantly however, am I missing some key element in how code first works? I tried the example above, ran Add-Migration and it does not add the lookup table for the enum.

    Read the article

  • WPF: How to bind RadioButtons to an enum?

    - by Sam
    I've got an enum like this: public enum MyLovelyEnum { FirstSelection, TheOtherSelection, YetAnotherOne }; I got a property in my DataContext: public MyLovelyEnum VeryLovelyEnum { get; set; } And I got three RadioButtons in my WPF client. <RadioButton Margin="3">First Selection</RadioButton> <RadioButton Margin="3">The Other Selection</RadioButton> <RadioButton Margin="3">Yet Another one</RadioButton> Now how do I bind the RadioButtons to the property for proper two-way-binding?

    Read the article

  • MSVC enum debugging

    - by oh boy
    Is there a quick way of outputting the names of enumerated values? I suppose you know what I mean, and at all this isn't possible as of course all of this data becomes irrelevant during compile process, but I'm using MSVC in debugging mode, so is it possible?

    Read the article

  • C# String Resource Values as Enum String Part values?

    - by JL
    Using VS2010 and .net V4.0 I would like to achieve the following: I already have 2 resource files in my project for 2 languages - English and Czech. I must say Resource Management in .net is excellent, I am suprised even to get code completion when implementing a String for example: string desc = Strings.ResourceManagerDesc This gets the string associated with the current culture of the thread. Now I am trying to create an Enum that can have the String portion of the Enum interpreted from the Strings resources. In the following way (This code DOES NOT WORK): public enum DownloadStatus { 1 = Strings.DownloadState_Complete, 2 = Strings.DownloadState_Failed, 3 = Strings.DownloadState_InProgress } This is a made up example, but you can see the point here. Since the above code won't work, is there a best practice way to achieve what I want?

    Read the article

  • Should I use Enumeration or Class stereotype in UML to represent a type directory table?

    - by Ivan
    Let's take 2 UML class model entities: One represents an actual Order and another represents an Orede Type. Any Order corresponds to one Type. A 2-way-naviglabe many Orders to one Type relation is meant. Order Type instances are, for example, "Request availability", "Request price", "Preorder", "Buy", "Cancel", "Request support", etc. Order Types are to be addable and editable in the resulting application. Should I model Order Type as Class or as Enumeration? From the data perspective I can't see the difference actually.

    Read the article

  • passing an "unknown enumeration" to a method

    - by firoso
    I'm currently trying to make a class that can register strings as identifiers and accociate them with different types of Enumerations, these enumerations are being evaluated only in so much that I am ensuring that when it's used, that the parameter passed to broadcast (messageType) is an instance of the associated Enum Type. This would work something like this: Diagnostics.RegisterIdentifier("logger", typeof(TestEnum)); Diagnostics.Broadcast("logger", TestEnum.Info, null, "Hello World", null); here's the code I currently have, I need to be able to verify that messageTypesEnum is contained in messageTypesFromIdentifier. private static Dictionary<string, Type> identifierMessageTypeMapping = new Dictionary<string, Type>(); private static List<IListener> listeners = new List<IListener>(); public static void RegisterIdentifier(string identifier, Type messageTypesEnum) { if (messageTypesEnum.BaseType.FullName == "System.Enum") { identifierMessageTypeMapping.Add(identifier, messageTypesEnum); } else { throw new ArgumentException("Expected type of messageTypesEnum to derive from System.Enum", "messageTypesEnum"); } } public static void Broadcast(string identifier, object messageType, string metaIdentifier, string message, Exception exception) { if (identifierMessageTypeMapping.ContainsKey(identifier)) { Type messageTypesFromIdentifier = identifierMessageTypeMapping[identifier]; foreach (var listener in listeners) { DiagnosticsEvent writableEvent = new DiagnosticsEvent(identifier, messageType, metaIdentifier, message, exception); listener.Write(writableEvent); } } }

    Read the article

  • Final enum in Thread's run() method

    - by portoalet
    Hi, Why is the Elvis elvis definition has to be final to be used inside the Thread run() method? Elvis elvis = Elvis.INSTANCE; // ----> should be final Elvis elvis = Elvis.INSTANCE elvis.sing(4); Thread t1 = new Thread( new Runnable() { @Override public void run() { elvis.sing(6); // --------> elvis has to be final to compile } } ); public enum Elvis { INSTANCE(2); Elvis() { this.x = new AtomicInteger(0); } Elvis(int x){ this.x = new AtomicInteger(x); } private AtomicInteger x = new AtomicInteger(0); public int getX() { return x.get(); } public void setX(int x) {this.x = new AtomicInteger(x);} public void sing(int x) { this.x = new AtomicInteger(x); System.out.println("Elvis singing.." + x); } }

    Read the article

  • Is it possible to create an enum whose object can't be created but can be used for readonly purpose

    - by Shantanu Gupta
    I created an enum where I stored some table names. I want it to be used to get the name of the table like ds.Tables[BGuestInfo.TableName.L_GUEST_TYPE.ToString()]. public enum TableName : byte { L_GUEST_TYPE = 0 ,L_AGE_GROUP = 1 ,M_COMPANY = 2 ,L_COUNTRY = 3 ,L_EYE_COLOR = 4 ,L_GENDER = 5 ,L_HAIR_COLOR = 6 ,L_STATE_PROVINCE = 7 ,L_STATUS = 8 ,L_TITLE = 9 ,M_TOWER = 10 ,L_CITY = 11 ,L_REGISTER_TYPE = 12 } This is my enum. Now I have not created any object of this enum so that no one can use it for other than read only purpose. For this enum to be accessible in outer classes as well I have to make it public which means some outer class can create its object as well. So what can i do so as to restrict its object creation.

    Read the article

  • C# enum to string auto-conversion?

    - by dcompiled
    Is it possible to have the compiler automatically convert my Enum values to strings so I can avoid explicitly calling the ToString method every time. Here's an example of what I'd like to do: enum Rank { A, B, C } Rank myRank = Rank.A; string myString = Rank.A; // Error: Cannot implicitly convert type 'Rank' to 'string' string myString2 = Rank.A.ToString(); // OK: but is extra work

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >