I am trying to refactor a switch statement that is like this:  private void Validate(DataTypeEnum dataType, string value, ...) {     switch(dataType)     {         case DataTypeEnum.Number:             var typedValue = int.Parse(value);             //Validation of typedValue             break;         case DataTypeEnum.Decimal:             var typedValue = Decimal.Parse(value);             //Validation of typedValue             break;         case DataTypeEnum.DateTime:             var typedValue = DateTime.Parse(value);             //Validation of typedValue             break;     } }   I would like to get rid of the switch statement and somehow replace it with a more object oriented construct. Any suggestions?  My ideal would be something like this:  private void Validate(DataTypeEnum dataType, string value, ...) {     Validate(value); } private void (Decimal value) {     //Validate } private void (DateTime value) {     //Validate }   Is there any elegant way to fix this?
63400
Seeing as C# can't switch on a Type (which I gather wasn't added as a special case because is relationships mean that more than one distinct case might apply), is there a better way to simulate switching on type other than this?  void Foo(object o) {     if (o is A)     {         ((A)o).Hop();     }     else if (o is B)     {         ((B)o).Skip();     }     else     {         throw new ArgumentException("Unexpected type: " + o.GetType());     } }
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 :)
122980
This is my code:  internal enum WindowsMessagesFlags {     WM_EXITSIZEMOVE      = 0x00000232,     WM_DISPLAYCHANGE     = 0x0000007e,     WM_MOVING            = 0x00000216, }  protected override void WndProc(ref Message m) {     switch(m.Msg) {         case (int)WindowsMessagesFlags.WM_DISPLAYCHANGE:             FixWindowSnapping();             break;         case (int)WindowsMessagesFlags.WM_EXITSIZEMOVE:             SaveWindowProperties();             break;         case (int)WindowsMessagesFlags.WM_MOVING:             KeepProperLocation(ref m);             break;     } }   Is there anyway to prevent the casting?
102402
I'm wanting to parse a string into a nullable int in C#.  ie. I want to get back either the int value of the string or null if it can't be parsed.  I was kind of hoping that this would work  int? val = stringVal as int?;   But that won't work, so the way I'm doing it now is I've written this extension method  public static int? ParseNullableInt(this string value) {     if (value == null || value.Trim() == string.Empty)     {         return null;     }     else     {         try         {             return int.Parse(value);         }         catch         {             return null;         }     } }      Is there a better way of doing this?  EDIT:  Thanks for the TryParse suggestions, I did know about that, but it worked out about the same.  I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?
105996
When I'm debugging, I often have to deal with methods that does not use an intermediate variable to store the return value :     private int myMethod_1()    {       return 12;    }     private int myMethod_2()    {       return someCall( someValue );    }   Well, in order to recreate a bug, I often have to change values on the fly. Here, I could want to see what happens when myMethode_1 return zero. Same thing for myMethod_2.  Is there a way to do that without modifying the code ? What I would like to do, it's to place a breakpoint on the return line (or on the closing bracket) and type-in a new return value.  Note : I'm using Visual Studio 2005 and Visual Studio 2008.  Thank !
44272
EDIT:  I found out that I can get it to compile if I cast the IMetadataType object to the TMetadata type.  Why do I need to do this?  EDIT #2:  The "Values" property is a .NET dictionary of type &lt;TMetadata, TData&gt;.  I have this generic method:  private void FillMetadata&lt;TMetadata, TData&gt;     (Metadata&lt;TMetadata, TData&gt; oMetadata) where TMetadata : IMetadataType {     IMetadataType o;     oMetadata.Values.Add(o, (TData)(object)GetValue()); }   I have stripped the implementation to simplify it (I actually use a real object, not the IMetadataType declared here).  My question is, why doesn't this compile?  The compile error is on the Add() method:  "cannot convert from 'IMetadataType' to 'TMetadata'."  Isn't that what the "where" clause on the method is for?  What am I missing?
56034
I doubt I am the only one who has come up with this solution, but if you have a better one please post it here. I simply want to leave this question here so I and others can search it later.   I needed to tell whether a valid date had been entered into a text box and this is the code that I came up with. I fire this when focus leaves the text box.  try {     DateTime.Parse(startDateTextBox.Text); } catch {     startDateTextBox.Text = DateTime.Today.ToShortDateString(); }
76714
I've always been of the opinion that large switch statements are a symptom of bad OOP design.  In the past, I've read articles that discuss this topic and they have provided altnerative OOP based approaches, typically based on polymorphism to instantiate the right object to handle the case.  I'm now in a situation that has a monsterous switch statement based on a stream of data from a TCP socket in which the protocol consists of basically newline terminated command, followed by lines of data, followed by an end marker.  The command can be one of 100 different commands, so I'd like to find a way to reduce this monster switch statement to something more manageable.  I've done some googling to find the solutions I recall, but sadly, Google has become a wasteland of irrelevant results for many kinds of queries these days.  Are there any patterns for this sort of problem?  Any suggestions on possible implementations?    One thought I had was to use a dictionary lookup, matching the command text to the object type to instantiate.  This has the nice advantage of merely creating a new object and inserting a new command/type in the table for any new commands.    However, this also has the problem of type explosion.  I now need 100 new classes, plus I have to find a way to interface them cleanly to the data model.  Is the "one true switch statement" really the way to go?  I'd appreciate your thoughts, opinions, or comments.
57217
Compiling the following code and got the error of type illegal.  int main() {     // Compilation error - switch expression of type illegal     switch(std::string("raj"))     {     case"sda":     } }   You cannot use string in either switch or case. Why? Is there any solution that works nicely to support logic similar to switch on strings?
69100
As an example take the following code:  public enum ExampleEnum { FooBar, BarFoo }  public class ExampleClass : INotifyPropertyChanged {     private ExampleEnum example;      public ExampleEnum ExampleProperty      { get { return example; } { /* set and notify */; } } }   I want a to databind the property ExampleProperty to a ComboBox, so that it shows the options "FooBar" and "BarFoo" and works in mode TwoWay. Optimally I want my ComboBox definition to look something like this:  &lt;ComboBox ItemsSource="What goes here?" SelectedItem="{Binding Path=ExampleProperty}" /&gt;   Currently I have handlers for the ComboBox.SelectionChanged and ExampleClass.PropertyChanged events installed in my Window where I do the binding manually.  Is there a better or some kind of canonical way? Would you usually use Converters and how would you populate the ComboBox with the right values? I don't even want to get started with i18n right now.  Edit  So one question was answered: How do I populate the ComboBox with the right values.  Retrieve Enum values as a list of strings via an ObjectDataProvider from the static Enum.GetValues method:  &lt;Window.Resources&gt;     &lt;ObjectDataProvider MethodName="GetValues"         ObjectType="{x:Type sys:Enum}"         x:Key="ExampleEnumValues"&gt;         &lt;ObjectDataProvider.MethodParameters&gt;             &lt;x:Type TypeName="ExampleEnum" /&gt;         &lt;/ObjectDataProvider.MethodParameters&gt;     &lt;/ObjectDataProvider&gt; &lt;/Window.Resources&gt;   This I can use as an ItemsSource for my ComboBox:  &lt;ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"/&gt;
37897
There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?
55833
I have some client-side validation against a text box, which only allows numbers up to two decimal places with no other input.  This script was a basis for entering numeric values only, however it needs to be adapted so it can take a decimal point followed by only up to two decimal places.  I've tried things such as /[^\d].\d{0,2}, but then the replacement call wouldn't work, and I've got no idea how to do it.  Code  &lt;script type="text/JavaScript"&gt;   function valid(f) {     if (!/^\d*$/.test(f.value)) {       f.value = f.value.replace(/[^\d]/g,"");       alert("Invalid number");     }   } &lt;/script&gt;     Note  I need to match an empty string. If an empty string is provided and the form is submitted, the value defaults back to zero.
118273
I'm trying to parse json response.. but keep getting this error      Invalid conversion from runtime type List ANY> to Map String,ANY>   Map&lt;String, Object&gt; MapLv3 = new Map&lt;String, Object&gt;();      Integer x2 = 0; for (Object oh : CallsList){     MapLv3.put(String.valueof(x2), oh);     x2++; } index = x2; System.debug('Map Lv 3 ==&gt;'+MapLv3);  Map&lt;String, Map &lt;String, Object&gt;&gt; Map3 = new Map&lt;String, Map &lt;String, Object&gt;&gt;(); for (Integer a2 = 0; a2 &lt; index; a2++){     Map3.put(String.valueof(a2),(Map&lt;String,Object&gt;) MapLv3.get(String.valueof(a2))); } System.debug('Segment ==&gt;'+Map3.get('0').get('segments'));
42580
What are the ways to eliminate the use of switch in code?
22847
Suppose we have some named enums:  enum MyEnum {       FOO,       BAR = 0x50 };   What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum.  char* enum_to_string(MyEnum t);   And a implementation with something like this:  char* enum_to_string(MyEnum t){       switch(t){          case FOO:             return "FOO";          case BAR:             return "BAR";          default:             return "INVALID ENUM";       }  }   The gotcha is really with typedefed enums, and unnamed C style enums. Does anybody know something for this?  EDIT: The solution should not modify my source, except for the generated functions. The enums are in an API, so using the solutions proposed until now is just not an option.
56847
This is an extension of .  So, using the answer from the previous question I mentioned, I am able to make a generic utility that would convert/parse an Enumeration to a String.  Now the only problem I have with my solution is, I can't seem to refactor the code to my liking. It works the way I want it to, but it is a tad more on the code heavy side than I had hoped for. I was curious if there was a design pattern (or any other way to code it) to help solve this issue. I am thinking there is a creational design pattern that will help in this case. I would be easy if I had lambda expression but, Apex is not quite there yet ;).  The code I use has kind of patterns dug into it already. It uses the Strategy, Factory, and Template(ish) pattern I believe. I have the resources to find something to solve this issue (my favorite Design Pattern books), but nothing I can think of jumps out at me.  Here is the code for my utility for just one enumeration:  private interface EnumerationToStringHelper {     List&lt;Object&gt; ProvideEnumerationValues();     Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue); }  private class ExampleEnumToStringHelper implements EnumerationToStringHelperExampleEnum {     public List&lt;Object&gt; ProvideEnumerationValues(){ return (List&lt;Object&gt;)ExampleEnum.values(); }     public Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue)     {         return  ((ExampleEnum)enumerationValue).name().equalsIgnoreCase(possibleEnumeration);     } }  private static Map&lt;Type, EnumerationToStringHelper&gt; TypeToEnumerationMap;  private static void PopulateTypeToEnumerationMap() {     TypeToEnumerationMap = new Map&lt;Type, EnumerationToStringHelper&gt;     {         Type.forName('ExampleEnum') =&gt; new ExampleEnumToStringHelper()     }; }  public static Object ConvertStringToEnumeration(Type enumerationType, String possibleEnumeration) {     if(possibleEnumeration == null) return null;     if(TypeToEnumerationMap == null)         PopulateTypeToEnumerationMap();      EnumerationToStringHelper conversionAction = TypeToEnumerationMap.get(enumerationType);      if(conversionAction == null)         throw new EnumerationToStringException('The Type you enter is either a) not an enumeration or b) not a supported enumeration.');      for(Object particalarEnumValue : conversionAction.ProvideEnumerationValues())         if(conversionAction.CompareEnumerationToString(possibleEnumeration, particalarEnumValue))             return particalarEnumValue;     return null; }   public class EnumerationToStringException extends Exception { }   Now in order to use the utility, it is exactly what I hoped for.  return (ExampleEnum)RT_GeneralUtilities.ConvertStringToEnumeration(Type.forName('ExampleEnum'), 'Testing');   It is a little long, but it beats having the entire for loop for 12 or more different Enum types. That is why I wanted to build the utility - essentially for better readability and test coverage purposes.  The downside with this is I have to make a helper for every single Enum type. So it makes it kind of an eyesore maintainability-wise.    I was hoping there was a pattern I could implement to assuage that eyesore and make it appealing on both sides. Any suggestions?
27507
What is the benefit/downside to using a switch statement vs. an if/else in C#.  I can't imagine there being that big of a difference, other than maybe the look of your code. Is there any reason why the resulting IL or associated runtime performance would be radically different? Related: