Allow argument in default case switch #2097
-
Like var someDictionary = new Dictionary<string,object>();
////
switch(someDictionary["TT"])
{
case null: return "";
case string s: return s;
case int i: return i.ToString();
default obj: throw new Exception("Not support type : " + (obj?.GetType() ?? "null"));
} The |
Beta Was this translation helpful? Give feedback.
Replies: 14 comments
-
The switch(someDictionary["TT"])
{
case null: return "";
case string s: return s;
case int i: return i.ToString();
case var obj: throw new Exception("Not support type : " + (obj?.GetType().FullName ?? "null"));
} |
Beta Was this translation helpful? Give feedback.
-
@yaakov-h Do Are there really not any difference between |
Beta Was this translation helpful? Give feedback.
-
switch (someDictionary["TT"])
{
case null: return "";
case string s: return s;
case int i: return i.ToString();
case var obj: throw new Exception($"Unsupported type: {obj.GetType()}");
}
Console.WriteLine("This code is unreachable."); // CS0162: Unreachable code detected
From an IL perspective, the only difference is
|
Beta Was this translation helpful? Give feedback.
-
This is untrue. the 'var' pattern matches 'null'. |
Beta Was this translation helpful? Give feedback.
-
Oops, I accidentally had |
Beta Was this translation helpful? Give feedback.
-
No worries :) |
Beta Was this translation helpful? Give feedback.
-
Thanks all |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
@gafter So should we still have this proposal as separate case from |
Beta Was this translation helpful? Give feedback.
-
I would not. You can still get he behavior desired from |
Beta Was this translation helpful? Give feedback.
-
@CyrusNajmabadi If the default one is the shortest logic to write I would place it on the top of switch |
Beta Was this translation helpful? Give feedback.
-
so move it to the end. :) adding a full language feature just so you can put the final case of the switch at the top of the switch seems very unnecessary. |
Beta Was this translation helpful? Give feedback.
-
@CyrusNajmabadi |
Beta Was this translation helpful? Give feedback.
-
Then just rewrite it. Adding a language feature to support this exact coding pattern seems unnecessary. |
Beta Was this translation helpful? Give feedback.
The
var
pattern already matches anything, i.e.: