Typeof

Last updated

typeof, alternately also typeOf, and TypeOf, is an operator provided by several programming languages to determine the data type of a variable. This is useful when constructing programs that must accept multiple types of data without explicitly specifying the type.

Contents

In languages that support polymorphism and type casting, the typeof operator may 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 returns the true, original type of the object, 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, to some degree, in C (as part of nonstandard extensions and proposed standard revisions), [4] [5] the typeof operator returns the static type of the operand. That is, it evaluates to the declared type at that instant in the program, irrespective of its original form. These languages usually have other constructs for obtaining run-time type information, such as typeid.

Examples

C#

In C#:

// Given an object, returns if it is an integer.// The "is" operator can be also used to determine this.publicstaticboolIsInteger(objecto){returno.GetType()==typeof(int);}

C

As of C23 typeof is a part of the C standard. The operator typeof_unqual was also added which is the same as typeof, except it removes cvr-qualification and atomic qualification. [6] [7]

In a non-standard (GNU) extension of the C programming language, typeof may be used to define a general macro for determining the maximum value of two parameters:

#define max(a,b) ({ typeof (a) _a = (a); typeof (b) _b = (b); _a > _b ? _a : _b; })


Java

In Java the keyword is instanceof. [8]

booleanisNumber(Objectobj){returnobjinstanceofNumber;}

Note that obj instanceof Number is not the same as obj.getClass() == Number.class, as instanceof will return true with all subclasses of Number and the equality test will not.

There is a preview feature introduced in Java 23 that allows it to be used with primitives as well. [9]

// returns true when num can be converted to an int without losing informationbooleanisInt(floatnum){returnnuminstanceofint;}

JavaScript

In JavaScript:

functionisNumber(n){return(typeofn==='number');}

TypeScript

In TypeScript: [10]

function(param:typeofexistingObject){...}
letnewObject:typeofexistingObject;

VB.NET

In VB.NET, the C# variant of "typeof" should be translated into the VB.NET's GetType method. The 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.

DimrefIntegerAsObject=2MsgBox("TypeOf Object[Integer] Is Integer? "&TypeOfrefIntegerIsInteger)MsgBox("TypeOf Object[Integer] Is Double? "&TypeOfrefIntegerIsDouble)DimrefFormAsObject=NewSystem.Windows.Forms.FormMsgBox("TypeOf Object[Form] Is Form? "&TypeOfrefFormIsSystem.Windows.Forms.Form)MsgBox("TypeOf Object[Form] Is Label? "&TypeOfrefFormIsSystem.Windows.Forms.Label)MsgBox("TypeOf Object[Form] Is Control? "&TypeOfrefFormIsSystem.Windows.Forms.Control)MsgBox("TypeOf Object[Form] Is IComponent? "&TypeOfrefFormIsSystem.ComponentModel.IComponent)

See also

Related Research Articles

VBScript is a deprecated programming language for scripting on Microsoft Windows using Component Object Model (COM) based on classic Visual Basic and Active Scripting.

In object-oriented (OO) and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.

<span class="mw-page-title-main">Visual Basic (.NET)</span> Object-oriented computer programming language

Visual Basic (VB), originally called Visual Basic .NET (VB.NET), is a multi-paradigm, object-oriented programming language, implemented on .NET, Mono, and the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visual Basic language, the last version of which was Visual Basic 6.0. Although the ".NET" portion of the name was dropped in 2005, this article uses "Visual Basic [.NET]" to refer to all Visual Basic languages released since 2002, in order to distinguish between them and the classic Visual Basic. Along with C# and F#, it is one of the three main languages targeting the .NET ecosystem. Microsoft updated its VB language strategy on 6 February 2023, stating that VB is a stable language now and Microsoft will keep maintaining it.

In computer science, primitive data types are a set of basic data types from which all other data types are constructed. Specifically it often refers to the limited set of data representations in use by a particular processor, which all compiled programs must use. Most processors support a similar set of primitive data types, although the specific representations vary. More generally, primitive data types may refer to the standard data types built into a programming language. Data types which are not primitive are referred to as derived or composite.

In computing, type introspection is the ability of a program to examine the type or properties of an object at runtime. Some programming languages possess this capability.

In computer science, a union is a value that may have any of multiple representations or formats within the same area of memory; that consists of a variable that may hold such a data structure. Some programming languages support a union type for such a data type. In other words, a union type specifies the permitted types that may be stored in its instances, e.g., float and integer. In contrast with a record, which could be defined to contain both a float and an integer; a union would hold only one at a time.

In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. In some languages, particularly C++, function objects are often called functors.

<span class="mw-page-title-main">Foreach loop</span> Control flow statement for traversing items in a collection

In computer programming, foreach loop is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

<span class="mw-page-title-main">Boolean data type</span> Data having only values "true" or "false"

In computer science, the Boolean is a data type that has one of two possible values which is intended to represent the two truth values of logic and Boolean algebra. It is named after George Boole, who first defined an algebraic system of logic in the mid 19th century. The Boolean data type is primarily associated with conditional statements, which allow different actions by changing control flow depending on whether a programmer-specified Boolean condition evaluates to true or false. It is a special case of a more general logical data type—logic does not always need to be Boolean.

In some programming languages, const is a type qualifier that indicates that the data is read-only. While this can be used to declare constants, const in the C family of languages differs from similar constructs in other languages in that it is part of the type, and thus has complicated behavior when combined with pointers, references, composite data types, and type-checking. In other languages, the data is not in a single memory location, but copied at compile time for each use. Languages which use it include C, C++, D, JavaScript, Julia, and Rust.

<span class="mw-page-title-main">JavaScript syntax</span> Set of rules defining correctly structured programs

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

this, self, and Me are keywords used in some computer programming languages to refer to the object, class, or other entity which the currently running code is a part of. The entity referred to thus depends on the execution context. Different programming languages use these keywords in slightly different ways. In languages where a keyword like "this" is mandatory, the keyword is the only way to access data and methods stored in the current object. Where optional, these keywords can disambiguate variables and functions with the same name.

C# and Visual Basic (.NET) are the two main programming languages used to program on the .NET framework.

Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type. In statically typed languages, a nullable type is an option type, while in dynamically typed languages, equivalent behavior is provided by having a single null value.

<span class="mw-page-title-main">Visual Basic (classic)</span> Microsofts programming language based on BASIC and COM

Visual Basic (VB) before .NET, sometimes referred to as Classic Visual Basic, is a third-generation programming language, based on BASIC, and an integrated development environment (IDE), from Microsoft for Windows known for supporting rapid application development (RAD) of graphical user interface (GUI) applications, event-driven programming and both consumption and development of components via the Component Object Model (COM) technology.

The computer programming language, C#, introduces several new features in version 2.0. These include:

Windows Runtime (WinRT) is a platform-agnostic component and application architecture first introduced in Windows 8 and Windows Server 2012 in 2012. It is implemented in C++ and officially supports development in C++, Rust/WinRT, Python/WinRT, JavaScript-TypeScript, and the managed code languages C# and Visual Basic (.NET) (VB.NET).

References

  1. "TypeOf Operator (Visual Basic)". MSDN . Archived from the original on Nov 28, 2016.
  2. "typeof (C#)". MSDN. Archived from the original on Sep 10, 2016.
  3. "Declarations - D Programming Language 1.0". Digital Mars. Dec 30, 2012. Archived from the original on Oct 7, 2023.
  4. "Typeof" in "Using the GNU Compiler Collection".
  5. Meneide, JeanHeyd (2021-03-07). "Not-So-Magic - typeof(…) in C | r2". Open Standards. Retrieved 2021-12-02.
  6. "N2927: Not-so-magic - typeof for C". Open Standards. 2022-02-02. Archived from the original on Dec 1, 2023.
  7. "Consider renaming remove_quals" (PDF). Open Standards. 2022-02-06. Archived (PDF) from the original on Feb 17, 2024.
  8. https://docs.oracle.com/javase/specs/jls/se23/html/jls-15.html#jls-15.20.2
  9. https://docs.oracle.com/en/java/javase/23/docs/specs/primitive-types-in-patterns-instanceof-switch-jls.html
  10. "Using 'typeof' to infer a type". Learn TypeScript. Retrieved 2022-01-28.