typeof

typeof (alternately typeOf or TypeOf) is an operator provided by several programming languages which determines the data type of a given variable. This can be useful when constructing parts of programs that need to accept many types of data but may need to take different action depending on the type of data provided.

In languages that support polymorphism and type casting, the typeof operator can have one of two distinct meanings when applied to an object. In some languages, such as Visual Basic,[1] the typeof operator returns the dynamic type of the object. That is, it tells the program what the true, original type of the object is, irrespective of any type casting. In these languages, the typeof operator is the method for obtaining run-time type information.

In other languages, such as C#[2] or D[3] and some nonstandard extensions to C and C++,[4] the typeof operator returns the static type of the object. That is, it tells the program what type the object is declared to be at that point in the program, irrespective of its original form. These languages usually have other constructs for obtaining run-time type information, such as typeid.

Examples

  #define max(a,b) \
       ({ typeof (a) _a = (a); \
           typeof (b) _b = (b); \
         _a > _b ? _a : _b; })
// Given an object, returns if it is an integer.
// The "is" operator can be also used to determine this.
public static bool IsInteger(object o) {
  return ( o.GetType() == typeof(int) );
}

The C# variant of "typeof" should be translated into the VB.NET's GetType method. TypeOf keyword in VB.NET is used to compare an object reference variable to a data type.

The following example uses TypeOf...Is expressions to test the type compatibility of two object reference variables with various data types.

Dim refInteger As Object = 2
MsgBox("TypeOf Object[Integer] Is Integer? " & TypeOf refInteger Is Integer)
MsgBox("TypeOf Object[Integer] Is Double? " & TypeOf refInteger Is Double)
Dim refForm As Object = New System.Windows.Forms.Form
MsgBox("TypeOf Object[Form] Is Form? " & TypeOf refForm Is System.Windows.Forms.Form)
MsgBox("TypeOf Object[Form] Is Label? " & TypeOf refForm Is System.Windows.Forms.Label)
MsgBox("TypeOf Object[Form] Is Control? " & TypeOf refForm Is System.Windows.Forms.Control)
MsgBox("TypeOf Object[Form] Is IComponent? " & TypeOf refForm Is System.ComponentModel.IComponent)
function isNumber(n)
{
  return ( typeof n === 'number' );
}

See also

References

This article is issued from Wikipedia - version of the Sunday, April 05, 2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.