|A long time ago, Eric wrote:
Of course, Eric is always right !
Quote:Any time you find yourself switching on a type in a generic you are almost certainly doing something wrong. Generics should be generic; they should operate identically completely independent of the type.
If T can only be int or string then don't write your code this way at all in the first place. Write two methods, one that returns an int and one that returns a string.
I thought the new pattern-matching facilities in C# 7,8 might allow me to simplify a 'Switch based on a Generic Type; here's a compilable (VS 2019, FrameWork 4.8) example:
public TKey GetNextKey(TKey key = default(TKey))
if (! KeysUsed.Contains(key))
CurrentKey = key;
case Type _ when KeyType == typeof(Int32):
int i = (Int32) (object) key + 1;
CurrentKey = (TKey)(object) i;
case Type _ when KeyType == typeof(string):
string s = (string) (object) key;
s += GetAGuid();
CurrentKey = (TKey)(object)s;
throw new ArgumentException("unsupported TKey Type");
}Okay, if you think "case Type _ when KeyType == typeof(Int32):" is simplification ... game over.
What really irritates me is the conversions to object necessary here. This issue came up in a QA question here in 2016; see FES_SiteCore's solution: [^]
references: Mads Torgensen on C# 8 patterns: [^], ReSharper recent blog: [^]
«Where is the Life we have lost in living? Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?» T. S. Elliot
modified 18-Jul-19 10:32am.