Typeof. The C# typeof operator returns Type objects. It is often used as a parameter or as a variable or field. It is part of an expression that acquires the Type pointer.
Some methods, like Enum.Parse, require a Type object, and typeof can get us this object. We use the typeof operator to get more information about a class.
Tip This program calls ToString on the Type pointers—this returns a string representation of the type.
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
}
}System.Char
System.Int32
System.Byte
System.IO.Stream
System.IO.TextWriter
System.Array
System.Int32[]
Enum example. Some common uses of the typeof operator are the Enum static methods, the DataTable class and similar classes, and the ArrayList conversion methods.
Here We use Enum.Parse with a typeof argument. With typeof, we get a Type and we use this as the first argument.
using System;
enum AnimalType
{
Bird
}
class Program
{
public static void Main()
{
string name = "Bird";
// Use Enum.Parse with typeof argument.
var result = Enum.Parse(typeof(AnimalType), name);
// Test result.
if ((AnimalType)result == AnimalType.Bird)
{
Console.WriteLine("OK");
}
}
}OK
Summary. Typeof is an operator. We assigned the result of typeof expressions to a Type field or variable. There are many common uses of the typeof operator in .NET.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 12, 2024 (new example).