using System;
class Program {
static void Main() {
Console.WriteLine(typeof(int).Name);
Console.WriteLine(typeof(int).FullName);
Console.WriteLine(typeof(string).Name);
}
}
Output
Int32
System.Int32
String
How It Works
int is Int32. The C# keyword int is a shortcut for System.Int32.
FullName includes the namespace. That is why it prints System.Int32.
Name is short. Just the type name without the namespace.
Example 2 — Compare with GetType()
Check the real type of an object at run time.
C#
using System;
class Program {
static void Main() {
object value = "hello";
Console.WriteLine(value.GetType() == typeof(string));
Console.WriteLine(value.GetType() == typeof(int));
}
}
Output
True
False
How It Works
GetType() looks at the object. It tells you the real type right now.
typeof names a type. It gives the Type to compare against.
Equal types. A string is a string, so the first line is True.
Example 3 — typeof with Arrays and Generics
See how arrays, generics, and your own classes appear.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Console.WriteLine(typeof(int[]).Name);
Console.WriteLine(typeof(List<int>).Name);
Console.WriteLine(typeof(Program).Name);
}
}
Output
Int32[]
List`1
Program
How It Works
Arrays. The name ends with [].
Generics.List`1 means a generic type with one type argument.
Your own class.typeof(Program) works for classes you write.
Frequently Asked Questions
It returns the System.Type object for a type name, such as typeof(int) or typeof(string).
typeof takes a type name at compile time. GetType() is called on an object and returns its real type at run time.
No. typeof needs a type name. Use variable.GetType() for a variable.
It returns Int32, because int is an alias for System.Int32.
Use it to compare types, read type names, or pass a Type to methods such as Activator or reflection APIs.