Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

typeof (C# Reference)

Used to obtain the System.Type object for a type. A typeof expression takes the following form:

System.Type type = typeof(int);

To obtain the run-time type of an expression, you can use the .NET Framework method GetType, like this:

int i = 0;
System.Type type = i.GetType();

The typeof operator can also be used on open generic types. Types with more then one type parameter must have the appropriate number of commas in the specification. The typeof operator cannot be overloaded.

// cs_operator_typeof.cs
using System;
using System.Reflection;

public class SampleClass
{
   public int sampleMember;
   public void SampleMethod() {}

   static void Main()
   {
      Type t = typeof(SampleClass);
      // Alternatively, you could use
      // SampleClass obj = new SampleClass();
      // Type t = obj.GetType();

      Console.WriteLine("Methods:");
      MethodInfo[] methodInfo = t.GetMethods();

      foreach (MethodInfo mInfo in methodInfo)
         Console.WriteLine(mInfo.ToString());

      Console.WriteLine("Members:");
      MemberInfo[] memberInfo = t.GetMembers();

      foreach (MemberInfo mInfo in memberInfo)
         Console.WriteLine(mInfo.ToString());
   }
}

Output

 
Methods:
Void SampleMethod()
System.Type GetType()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
Members:
Void SampleMethod()
System.Type GetType()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
Void .ctor()
Int32 sampleMember

This sample uses the GetType method to determine the type used to contain the result of a numeric calculation. This depends on the storage requirements of the resulting number.

// cs_operator_typeof2.cs
using System;
class GetTypeTest 
{
   static void Main() 
   {
      int radius = 3;
      Console.WriteLine("Area = {0}", radius * radius * Math.PI);
      Console.WriteLine("The type is {0}", 
                        (radius * radius * Math.PI).GetType()
      );
   }
}

Output

 
Area = 28.2743338823081
The type is System.Double

For more information, see the following sections in the C# Language Specification:

  • 7.5.11 The typeof operator

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2015 Microsoft