Note that there are some explanatory texts on larger screens.

plurals
  1. POAlternative for switch that only calls methods based on cases values
    text
    copied!<p>Is there a possible way to write the next switch in some shorter, readable code?</p> <pre><code>switch (SomeValue) { case "001": return DoMethod1(); break; case "002": return DoMethod2(); break; //etc.. } </code></pre> <p>I was thinking in some way like </p> <pre><code>Dictionary&lt;string, Func&lt;int&gt;&gt; MethodsByValue = new Dictionary&lt;string, Func&lt;int&gt;&gt;() { { "001", DoMethod1 }, { "002", DoMethod2 }, } </code></pre> <p>and call this by doing</p> <pre><code>return MethodsByValue[SomeValue](); </code></pre> <p>But is this even possible? Or am I thinking way to far out of the box. I couldn't find anyting like this but then again, I don't know the keywords for this if it is possible.</p> <p>EDIT: To answer the request of Lasse V. Karlsen:</p> <p>This is how the code is in my project. Changed names at some places cause original names doesn't matter cause it is in my mother language.</p> <pre><code>public string GetRecord420(Dictionary&lt;DataClass, object&gt; dictionaryName) { // some code here } public string GetRecord421(Dictionary&lt;DataClass, object&gt; dictionaryName) { // some code here } //(Temperary) solution with the switch statement in a wrapper: public string GetRecordByString(string s, Dictionary&lt;DataClass, object&gt; dictionaryName) { switch (s) { case "320": return GetRecord420(dictionaryName); case "321": return GetRecord421(dictionaryName); default: return String.Empty; } } //How I hoped it could be, with a mapping dictionary. public Dictionary&lt;string, Func&lt;string, Dictionary&lt;DataClass, object&gt;&gt;&gt; MethodByString = new Dictionary&lt;string, Func&lt;string, Dictionary&lt;DataClass, object&gt;&gt;&gt;() { { "320", GetRecord420 }, { "321", GetRecord421 }, } </code></pre> <p>DataClass is an Entity class, which stores some column data (column name, column type, etc.).</p> <p>I tried the dictionary part, but it gives me the error: Cannot convert from method group to System.Func&lt;...>. </p> <p>Changing to () => GetRecord420 gives me the error: Cannot convert lambda to delegate type System.Func&lt;...> because some of the return types in the block are not implicitly convertible to the delegate return type.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload