using System;
class Program {
static void Main() {
Console.WriteLine("hello".GetTypeCode());
Console.WriteLine(42.GetTypeCode());
Console.WriteLine(3.14.GetTypeCode());
}
}
Output
String
Int32
Double
How It Works
String value."hello" reports String.
Whole number.42 is an int, so Int32.
Decimal literal.3.14 is a double by default.
Example 2 — Type.GetTypeCode() and Numbers
Get a code from a type. Casting a TypeCode to int shows its number.
C#
using System;
class Student { }
class Program {
static void Main() {
Console.WriteLine(Type.GetTypeCode(typeof(bool)));
Console.WriteLine(Type.GetTypeCode(typeof(Student)));
Console.WriteLine((int)TypeCode.Int32);
}
}
Output
Boolean
Object
9
How It Works
Built-in type.bool gives Boolean.
Your own class.Student is not a basic type, so it gives Object.
Enum value.(int)TypeCode.Int32 prints 9.
Example 3 — Switch on a TypeCode
Decide whether an object holds a number.
C#
using System;
class Program {
static bool IsNumber(object value) {
switch (Type.GetTypeCode(value.GetType())) {
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
return false;
}
}
static void Main() {
object[] items = { 5, "text", 3.5, true };
foreach (object item in items) {
Console.WriteLine($"{item}: {IsNumber(item)}");
}
}
}
Output
5: True
text: False
3.5: True
True: False
How It Works
Find the type.value.GetType() gives the real type of the object.
Get its code.Type.GetTypeCode() turns it into an enum value.
Switch. Number codes return true. Everything else returns false.
Frequently Asked Questions
It is an enum that names the basic .NET types, such as Int32, Double, String, and Boolean.
Call value.GetTypeCode() on a built-in value, or Type.GetTypeCode(typeof(T)) for a type.
TypeCode.Object. TypeCode only describes basic built-in types.
It is common in conversion code and in switch statements over values stored as object.
Use is for most checks. TypeCode is handy when you want one switch over many numeric types.