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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 12, 2024 (new example).