If I need some type-specific code, I could use typeof
for example:
private static bool IsNumericType(Type type)
{
return type == typeof(int) || type == typeof(decimal); //etc
}
But I could also use the enum TypeCode
private static bool IsNumeric(TypeCode objTypeCode)
{
return objTypeCode == TypeCode.Int16 || objTypeCode == TypeCode.Int32 || objTypeCode == TypeCode.Int64; // etc ||
}
What is the benefit of using TypeCode
over typeof
from an architectural and performance viewpoint? In which case should I use the one of the two?
FYI, the code to get the type
/ typeCode
from an value:
var type = value.GetType();
var typeCode = Convert.GetTypeCode(value);
PS: These examples are strongly simplified.
PS 2: If I pass the value, I could also use as
, is
etc. But In this case I don't like to send as the method doesn't need to know the value, only it's type.
TypeCode
works best when you are following several possible paths, and most or all of the logic can be done by examining the code alone as then switch
ing on that will be pretty efficient, and generally pretty clear.
In other cases you are likely to have as much logic inside the Object
branch as outside since that is the code for most types, in which case it tends not to be as useful to examine the code first unless perhaps the cases that are served well by it are also cases that come up particularly often.
Your IsNumeric
example is a good example of when TypeCode
works well as if you rewrite it to a switch you are answering with one virtual call to get the code and one switch of the sort that compiles to relatively efficient jumps rather than branch on multiple comparisons of different possible types.
Note that enum types have the same code as their underlying numeric types. Whether that counts as having those cases covered for free, or as a case you'll have to guard against separately depends on how you want to consider those types for whatever your purpose is.