I am returning a list of values, and I would like to assign each one to an enum for better search. I have few fields - such as Desc, Value and so on.. I would like each of them to have an assigned enum value. So Desc would be 10, Value 20 and so on. I am returning values like this      var articleData = new List&lt;Article&gt;();  foreach (var  textField in result.TextResult) {      var data = new Article       {           Desc = textField.Name + &quot;:&quot;,           Value = textField.Value,           Type = ....       };            articleData.Add(data);   }           public enum Type          {             None = 0,             Value = 10,             Desc = 20,             Title = 30,             ....         }  public class Article {         public string Value {get; set; }          public string Desc {get; set; }          public Type Type {get; set; }         }  Do you have any ideas?
7882
What's the best way to convert a string to an enumeration value in C#? I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the corresponding enumeration value. In an ideal world, I could do something like this: StatusEnum MyStatus = StatusEnum.Parse(&quot;Active&quot;);  but that isn't a valid code.
30518
How can an int be cast to an enum in C#?
19825
But here's an example:  Dim desiredType as Type if IsNumeric(desiredType) then ...   EDIT: I only know the Type, not the Value as a string.  Ok, so unfortunately I have to cycle through the TypeCode.  But this is a nice way to do it:   if ((desiredType.IsArray))       return 0;   switch (Type.GetTypeCode(desiredType))  {       case 3:       case 6:       case 7:       case 9:       case 11:       case 13:       case 14:       case 15:           return 1;  }  ;return 0;
72597
How would i create a multi value Dictionary in c#?  E.g. Dictionary&lt;T,T,T&gt; where the first T is the key and other two are values.  so this would be possible: Dictionary&lt;int,object,double&gt;  Thanks
66268
In a C++ project I'm working on, I have a flag kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be:   new record deleted record modified record existing record   Now, for each record I wish to keep this attribute, so I could use an enum:  enum { xNew, xDeleted, xModified, xExisting }   However, in other places in code, I need to select which records are to be visible to the user, so I'd like to be able to pass that as a single parameter, like:   showRecords(xNew | xDeleted);   So, it seems I have three possible appoaches:  #define X_NEW      0x01 #define X_DELETED  0x02 #define X_MODIFIED 0x04 #define X_EXISTING 0x08   or  typedef enum { xNew = 1, xDeleted, xModified = 4, xExisting = 8 } RecordType;   or   namespace RecordType {     static const uint8 xNew = 1;     static const uint8 xDeleted = 2;     static const uint8 xModified = 4;     static const uint8 xExisting = 8; }   Space requirements are important (byte vs int) but not crucial. With defines I lose type safety, and with enum I lose some space (integers) and probably have to cast when I want to do a bitwise operation. With const I think I also lose type safety since a random uint8 could get in by mistake.  Is there some other cleaner way?  If not, what would you use and why?  P.S. The rest of the code is rather clean modern C++ without #defines, and I have used namespaces and templates in few spaces, so those aren't out of question either.
12013
I've the enum type ReportTypeEnum that get passed between methods in all my classes but I then need to pass this on the URL so I use the ordinal method to get the int value. After I get it in my other JSP page, I need to convert it to back to an ReportTypeEnum so that I can continue passing it.   How can I convert ordinal to the ReportTypeEnum?  Using Java 6 SE.
1840
I met an interesting issue about C#. I have code like below.  List&lt;Func&lt;int&gt;&gt; actions = new List&lt;Func&lt;int&gt;&gt;();  int variable = 0; while (variable &lt; 5) {     actions.Add(() =&gt; variable * 2);     ++ variable; }  foreach (var act in actions) {     Console.WriteLine(act.Invoke()); }   I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s.  It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output.  Is there a way to work round this limit to have each action instance have its own captured variable?
92538
I'd like to create a Dictionary object, with string Keys, holding values which are of a generic type. I imagine that it would look something like this:  Dictionary&lt;string, List&lt;T&gt;&gt; d = new Dictionary&lt;string, List&lt;T&gt;&gt;();     And enable me to add the following:  d.Add("Numbers", new List&lt;int&gt;()); d.Add("Letters", new List&lt;string&gt;());   I know that I can do it for a list of strings, for example, using this syntax:  Dictionary&lt;string, List&lt;string&gt;&gt; d = new Dictionary&lt;string, List&lt;string&gt;&gt;(); d.Add("Key", new List&lt;string&gt;());   but I'd like to do it for a generic list if possible...  2 questions then:   Is it possible? What's the syntax?   Many thanks, Jon
9571
I realize that it seems to be a duplicate of  but my question has a slight difference (from my point of view):  Once I know that   I will not use my class with "techniques that only works on properties" and  I will not use validation code in the getter/setter.   Is there any difference (except the style/future development ones), like some type of control in setting the property?  Is there any additional difference between:  public string MyString { get; set; }   and   public string myString;   (I am aware that, that the first version requires C# 3.0 or above and that the compiler does create the private fields.)
43991
I have the following enumeration:  public enum AuthenticationMethod {     FORMS = 1,     WINDOWSAUTHENTICATION = 2,     SINGLESIGNON = 3 }   The problem however is that I need the word "FORMS" when I ask for AuthenticationMethod.FORMS and not the id 1.  I have found the following solution for this problem ():  First I need to create a custom attribute called "StringValue":  public class StringValue : System.Attribute {     private readonly string _value;      public StringValue(string value)     {         _value = value;     }      public string Value     {         get { return _value; }     }  }   Then I can add this attribute to my enumerator:  public enum AuthenticationMethod {     [StringValue("FORMS")]     FORMS = 1,     [StringValue("WINDOWS")]     WINDOWSAUTHENTICATION = 2,     [StringValue("SSO")]     SINGLESIGNON = 3 }   And of course I need something to retrieve that StringValue:  public static class StringEnum {     public static string GetStringValue(Enum value)     {         string output = null;         Type type = value.GetType();          //Check first in our cached results...          //Look for our 'StringValueAttribute'           //in the field's custom attributes          FieldInfo fi = type.GetField(value.ToString());         StringValue[] attrs =            fi.GetCustomAttributes(typeof(StringValue),                                    false) as StringValue[];         if (attrs.Length &gt; 0)         {             output = attrs[0].Value;         }          return output;     } }   Good now I've got the tools to get a string value for an enumerator. I can then use it like this:  string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);   Okay now all of these work like a charm but I find it a whole lot of work. I was wondering if there is a better solution for this.  I also tried something with a dictionary and static properties but that wasn't better either.
560
It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.  List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = sl;   results in Cannot implicitly convert type System.Collections.Generic.List&lt;string&gt; to System.Collections.Generic.List&lt;object&gt;  And then...  List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = (List&lt;object&gt;)sl;   results in Cannot convert type System.Collections.Generic.List&lt;string&gt; to System.Collections.Generic.List&lt;object&gt;  Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.
21008
I was wondering in C++ if I have an enum can I access the value at the second index?  For example I have  enum Test{hi, bye};   if I want 'hi', can I do something like Test[0], thanks.
16114
I want to add values to a lookupmulti field with c#. the form shows the field correctly but my code just won't work:  SPList list = SPContext.Current.Web.Lists["testlist"]; SPListItem item = list.GetItemById(someId); SPFieldLookupValueCollection fieldValues = new SPFieldLookupValueCollection(); foreach(int id in itemIds) {    fieldValues.Add(new SPFieldLookupValue {LookupId = id}); } item["lookupmultifield"] = fieldValues;   The code above is not exactly my code, but it's how i thought it should work.  FieldValues has 2 entries, but only the first is inserted in the lookupmulti field. can anyone help?
50228
I have a Linq to objects statement   var confirm = from l in lines.Lines   where (l.LineNumber == startline.LineNumber) || (l.LineNumber == endline.LineNumber)   select l;   The confirm object is returning an 'Object Null or Not A Reference' at at System.Linq.Enumerable.WhereListIterator`1.MoveNext()  If the result of the query was empty, it would just return an empty enumerator. I know for a fact that there are no null objects in the statement. Is it possible to step through the LINQ statement to see where it is falling over?  EDIT When I said I know for a fact that there are no null objects it turns out I was lying :[, but the question remains, though I am asuming the answer will be 'you can't really'  LINQPad is a good idea, I used it to teach myself LINQ, but I may start looking at it again as a debug / slash and burn style tool
90809
Does anyone know if there is a good equivalent to Java's Set collection in C#? I know that you can somewhat mimic a set using a Dictionary or a HashTable by populating but ignoring the values, but that's not a very elegant way.
16221
It is possible to add and remove elements from an enum in Java at runtime?  For example, could I read in the labels and constructor arguments of an enum from a file?    @saua, it's just a question of whether it can be done out of interest really. I was hoping there'd be some neat way of altering the running bytecode, maybe using  or something. I've also followed up with  because I realised I wasn't totally sure when an enum should be used.  I'm pretty convinced that the right answer would be to use a collection that ensured uniqueness instead of an enum if I want to be able to alter the contents safely at runtime.
5329
I'm building a function to extend the Enum.Parse concept that  Allows a default value to be parsed in case that an Enum value is not found Is case insensitive  So I wrote the following: public static T GetEnumFromString&lt;T&gt;(string value, T defaultValue) where T : Enum {     if (string.IsNullOrEmpty(value)) return defaultValue;     foreach (T item in Enum.GetValues(typeof(T)))     {         if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;     }     return defaultValue; }  I am getting a Error Constraint cannot be special class System.Enum. Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code. EDIT All suggestions below have been greatly appreciated, thanks. Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML) public static class EnumUtils {     public static T ParseEnum&lt;T&gt;(string value, T defaultValue) where T : struct, IConvertible     {         if (!typeof(T).IsEnum) throw new ArgumentException(&quot;T must be an enumerated type&quot;);         if (string.IsNullOrEmpty(value)) return defaultValue;          foreach (T item in Enum.GetValues(typeof(T)))         {             if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;         }         return defaultValue;     } }  EDIT: (16th Feb 2015) Christopher Currens has posted  below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page. EDIT 2: (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)