C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Metadata: The typeof operator uses reflection to access the metadata descriptions of the types.
Type: We display the string representation of these Type pointers. We assign the result of the typeof operator to a Type variable or field.
ConsoleToString: This program calls ToString on the Type pointers—this returns a string representation of the type.
C# program that uses typeof expressions
using System;
using System.IO;
class Program
{
static Type _type = typeof(char); // Store Type as field.
static void Main()
{
Console.WriteLine(_type); // Value type pointer
Console.WriteLine(typeof(int)); // Value type
Console.WriteLine(typeof(byte)); // Value type
Console.WriteLine(typeof(Stream)); // Class type
Console.WriteLine(typeof(TextWriter)); // Class type
Console.WriteLine(typeof(Array)); // Class type
Console.WriteLine(typeof(int[])); // Array reference type
}
}
Output
System.Char
System.Int32
System.Byte
System.IO.Stream
System.IO.TextWriter
System.Array
System.Int32[]
So: We can use nameof even on local variables. We use it here to get an argument's name (size) and a local's name (animal).
C# program that uses nameof
using System;
class Program
{
static void Test(int size)
{
// ... Write argument name with nameof.
Console.WriteLine(nameof(size));
Console.WriteLine(size);
// ... Use nameof on a local variable.
var animal = "cat";
Console.WriteLine(nameof(animal));
}
static void Main()
{
// Call method.
Test(100);
}
}
Output
size
100
animal
Info: We can store the results of the typeof expression. We can use this static Type field wherever we require the Type pointer.
Version 1: This code uses the typeof operator. If this returns null, the program is exited.
Version 2: This version of the code uses a cached static Type pointer. The same if-check is done in this loop as in version 1.
C# program that optimizes typeof
using System;
using System.Diagnostics;
class Program
{
static Type _type = typeof(Stopwatch);
const int _max = 100000000;
static void Main()
{
var s1 = Stopwatch.StartNew();
// Version 1: use typeof.
for (int i = 0; i < _max; i++)
{
Type type = typeof(Stopwatch);
if (type == null)
{
throw new Exception();
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
// Version 2: use static type cache.
for (int i = 0; i < _max; i++)
{
Type type = _type;
if (type == null)
{
throw new Exception();
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
_max).ToString("0.00 ns"));
}
}
Output
1.64 ns typeof expression
1.37 ns static type
Info: The .NET Framework has optimizations to compare multiple typeof expressions. This optimization is not always useful.
Tip: The lowercase types such as "char" and "int" are aliased to the framework types "System.Char" and "System.Int32" in mscorlib.dll.
Using System