I have a very basic question. In Java, it is possible to point attributes and variables to Enums, such as:  public enum DayTime{     Morning("Morning"),     Afternoon("Afternoon"),     Night("Night");      private string description;      Daytime(string description){         this.description = description;     }      public string getDescription(){         return description;     } }   Is it possible to apply the same concept to C#? I am trying to get modular descriptions to products, whereas their name, contents and characteristics would be shown in a string of text, and Enums looked like the best alternative to modify this text according to which characteristic is selected.
17522
I've been programming in Java for a while and just got thrown onto a project that's written entirely in C#.  I'm trying to come up to speed in C#, and noticed enums used in several places in my new project, but at first glance, C#'s enums seem to be more simplistic than the Java 1.5+ implementation.  Can anyone enumerate the differences between C# and Java enums, and how to overcome the differences?  (I don't want to start a language flame war, I just want to know how to do some things in C# that I used to do in Java).  For example, could someone post a C# counterpart to Sun's famous Planet enum example?  public enum Planet {   MERCURY (3.303e+23, 2.4397e6),   VENUS   (4.869e+24, 6.0518e6),   EARTH   (5.976e+24, 6.37814e6),   MARS    (6.421e+23, 3.3972e6),   JUPITER (1.9e+27,   7.1492e7),   SATURN  (5.688e+26, 6.0268e7),   URANUS  (8.686e+25, 2.5559e7),   NEPTUNE (1.024e+26, 2.4746e7),   PLUTO   (1.27e+22,  1.137e6);    private final double mass;   // in kilograms   private final double radius; // in meters   Planet(double mass, double radius) {       this.mass = mass;       this.radius = radius;   }   public double mass()   { return mass; }   public double radius() { return radius; }    // universal gravitational constant  (m3 kg-1 s-2)   public static final double G = 6.67300E-11;    public double surfaceGravity() {       return G * mass / (radius * radius);   }   public double surfaceWeight(double otherMass) {       return otherMass * surfaceGravity();   } }  // Example usage (slight modification of Sun's example): public static void main(String[] args) {     Planet pEarth = Planet.EARTH;     double earthRadius = pEarth.radius(); // Just threw it in to show usage      // Argument passed in is earth Weight.  Calculate weight on each planet:     double earthWeight = Double.parseDouble(args[0]);     double mass = earthWeight/pEarth.surfaceGravity();     for (Planet p : Planet.values())        System.out.printf("Your weight on %s is %f%n",                          p, p.surfaceWeight(mass)); }  // Example output: $ java Planet 175 Your weight on MERCURY is 66.107583 Your weight on VENUS is 158.374842 [etc ...]
56347
The  keyword does away with the need for an explicit type declaration and I have read with interest the  of when it might be appropriate.  I have also read about (but not used)  which seems to take things a step further by making it .  With Boo, both the type and the declaration can be implied.  Which leads me to wonder, why did the C# language designers bother to include a var keyword at all?    Update: Yes, var supports Anonymous types, but anonymous types by themselves do not necessitate the var keyword...  var anon = new { Name = "Terry", Age = 34 };   versus  anon = new { Name = "Terry", Age = 34 };
3048
Say I have an enum which is just public enum Blah {     A, B, C, D }  and I would like to find the enum value of a string, for example &quot;A&quot; which would be Blah.A. How would it be possible to do this? Is the  the method I need? If so, how would I use this?
79701
I'm used to work with Java where large amounts of examples are available. For various reasons I had to switch to C# and trying to do the following in SharpDevelop:  // Form has a menu containing a combobox added via SharpDevelop's GUI  // --- Variables languages = new string[2]; languages[0] = "English"; languages[1] = "German"; DataSet myDataSet = new DataSet();  // --- Preparation DataTable lTable = new DataTable("Lang"); DataColumn lName = new DataColumn("Language", typeof(string)); lTable.Columns.Add( lName ); for( int i=0; i&lt;languages.Length; i++ ) {     DataRow lLang = lTable.NewRow();     lLang["Language"] = languages[i];     lTable.Rows.Add(lLang); } myDataSet.Tables.Add(lTable);  // --- Handling the combobox mnuActionLanguage.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView; mnuActionLanguage.ComboBox.DisplayMember = "Language";   One would assume to see some values in the dropdown, but it's empty. Please tell me what I'm doing wrong ;(  EDIT: mnuActionLanguage.ComboBox.DataBind() is what I also found on the net, but it doesn't work in my case.  SOLUTION  mnuActionLanguage.ComboBox.BindingContext = this.BindingContext;   at the end solved the problem!
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 :)
24638
I read  and thought that would easily be solved (not that it isn't solvable without) if one could write:   @Override public String toString() {     return super.super.toString(); }   I'm not sure if it is useful in many cases, but I wonder why it isn't and if something like this exists in other languages.  What do you guys think?  EDIT: To clarify: yes I know, that's impossible in Java and I don't really miss it. This is nothing I expected to work and was surprised getting a compiler error. I just had the idea and like to discuss it.
118537
In C#, if you want a method to have an indeterminate number of parameters, you can make the final parameter in the method signature a params so that the method parameter looks like an array but allows everyone using the method to pass as many parameters of that type as the caller wants.  I'm fairly sure Java supports similar behaviour, but I cant find out how to do it.
89955
If I have the following enum:  public enum ReturnValue{     Success = 0,     FailReason1 = 1,     FailReason2 = 2     //Etc... }   Can I avoid casting when I return, like this:  public static int main(string[] args){     return (int)ReturnValue.Success; }   If not, why isn't an enum value treated as an int by default?
122391
I have a string like this:  string s = "This is my string";   I am creating a Telerik report and I need to define a textbox that is the width of my string. However the size property needs to be set to a Unit (Pixel, Point, Inch, etc).  How can I convert my string length into, say a Pixel so I can set the width?  EDIT:  I have tried getting a reference to the graphics object, but this is done in a class that inherits from Telerik.Reporting.Report.
75057
Is there a way in C# to import everything inside a namespace like there is in Java with the wildcard character?  import java.awt.*;
120955
I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string.  I would hope that there's a public method in the C# library like "public bool FormatAsXml(string text, out string formattedXmlText)", but it couldn't be that easy, could it?  Very specifically, what would the method "SomeMethod" have to be that would produce the output below?  string unformattedXml; string formattedXml;  unformattedXml = "&lt;?xml version=\"1.0\"?&gt;&lt;book&gt;&lt;author&gt;Lewis, C.S.&lt;/author&gt;&lt;title&gt;The Four Loves&lt;/title&gt;&lt;/book&gt;" formattedXml = SomeMethod(unformattedXml);  Console.WriteLine(formattedXml);   Output:  &lt;?xml version="1.0"?&gt;   &lt;book id="123"&gt;     &lt;author&gt;Lewis, C.S.&lt;/author&gt;     &lt;title&gt;The Four Loves&lt;/title&gt;   &lt;/book&gt;
81127
Would the following make the objects fulfill all charasteristics that enums have in JavaScript? Something like: my.namespace.ColorEnum = {     RED : 0,     GREEN : 1,     BLUE : 2 }  // later on  if(currentColor == my.namespace.ColorEnum.RED) {    // whatever }  Or is there some other way I can do this?
29175
What are attributes in .NET, what are they good for, and how do I create my own attributes?
47388
In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences. If this code: Console.WriteLine(someString);  produces: Hello World!  I want this code: Console.WriteLine(ToLiteral(someString));  to produce: \tHello\r\n\tWorld!\r\n
45776
I'm trying to do something like the following:  enum E;  void Foo(E e);  enum E {A, B, C};   which the compiler rejects.  I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why.  Can anyone explain?  Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I do not want the enum's values exposed - so, for example, I do not want anyone to know that E is defined as  enum E {     FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X }   as project X is not something I want my users to know about.  So, I wanted to forward declare the enum so I could put the private methods in the header file, declare the enum internally in the cpp, and distribute the built library file and header to people.  As for the compiler - it's GCC.
65595
Not quite an Attribute, not quite a Method. Stereotypes? &lt;&lt;get&gt;&gt; &lt;&lt;set&gt;&gt;?    I'm retro-modelling an existing system, so I need to clearly reflect that this is not the same as a readonly field or a methods pair (regardless of what the IL says), so I think I'll go with the stereotype, but I'll accept the language independant get_ set_ as a general solution. Thanks all for the sanity test.
275
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?