How to Check Object Types

Type Checking

The concept of "type" plays a crucial role as it pertains to data types. Within the .NET Runtime, a specialized type known as System.Type is defined, serving as a fundamental representation of various data types in the System. This System.Type diligently stores crucial type information within variables, properties, or fields. Remarkably, each class carefully crafted within the system is intrinsically associated with its own corresponding System.Type, bestowing upon it the capability to encapsulate and comprehend the underlying data type attributes.

Determine type of a variable

Getting datatype of a variable in c# asp.net vb.net

At runtime, every data type within the .NET framework is impeccably represented by an instance of System.Type. This invaluable System.Type object allows developers to access comprehensive information about the type, including its superclasses, methods, properties, fields, and more. Retrieving the System.Type object can be accomplished in two fundamental ways: firstly, by invoking the GetType method on a specific instance of an object; secondly, by utilizing the typeof operator followed by the name of the type. By employing either of these approaches, developers gain access to a wealth of essential details about the type at runtime, empowering them to perform dynamic and flexible operations within their applications.

typeof operator

The typeof operator serves as a valuable tool in obtaining the System.Type object for a specific data type in the .NET framework. This operator is commonly utilized as a parameter, variable, or field within the code. Its primary purpose lies in facilitating a compile-time lookup, wherein, given a symbol representing a class name, the corresponding Type object is retrieved. By utilizing the typeof operator, developers can efficiently access the metadata and essential information about the type during the compilation process. This feature enables static analysis and early binding, contributing to the robustness and efficiency of the code. The typeof operator proves invaluable in scenarios where the type information is required at compile time, empowering developers to make informed decisions and perform targeted operations within their applications.

C#
System.Type type = typeof(int); Console.WriteLine(type);
VB.Net
Dim type As System.Type = GetType(Integer) Console.WriteLine(type)

Output : System.Int32

GetType Method

The GetType method in C# is a virtual method present in the base Object class, and as such, it can be invoked on any object instance. This unique feature allows developers to dynamically retrieve the exact runtime type of the current instance during program execution. The concept of runtime type refers to the actual data type of an object as it exists in memory during runtime, rather than its static or declared type known at compile time. Since the runtime type is determined during program execution, it is regarded as a run-time concept, dynamically providing essential information about the object's concrete type. By utilizing the GetType() method, developers can access this runtime type information and make informed decisions based on the actual object type present in memory, enabling versatile and flexible coding practices.

C#
Console.WriteLine(i.GetType().FullName);
VB.Net
Dim i As Integer = 100 Console.WriteLine(i.[GetType]().FullName)

Output : System.Int32

Checking for variable type

The following example will clear about the usage of GetType Method and typeof operator.

C# Source Code
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int i = 100; Console.WriteLine(i.GetType().FullName); Console.WriteLine(typeof(int).Name); if (i.GetType() == typeof(int)) Console.WriteLine("Both are same"); else Console.WriteLine("Both are not same"); Console.ReadKey(); } } }

Final Output : Both are same

VB.Net Source Code
Module Module1 Sub Main() Dim i As Integer = 100 Console.WriteLine(i.[GetType]().FullName) Console.WriteLine(GetType(Integer).Name) If i.[GetType]() Is GetType(Integer) Then Console.WriteLine("Both are same") Else Console.WriteLine("Both are not same") End If Console.ReadKey() End Sub End Module

Final Output : Both are same

When and where to use GetType() or typeof

GetType() works at runtime and typeof() is a compile-time operator.

Various Ways to Check Object Types  c# asp.net

The GetType() method is a member of the Object class in C#, and it can be called on individual objects to retrieve the execution-time type of the object. This method is particularly useful when you need to obtain the type of an object dynamically during runtime rather than relying on the static or compile-time type. By invoking GetType(), you can access the actual runtime type of the object, allowing for dynamic behavior and decisions based on the specific type of the instance at runtime. This versatility makes GetType() a powerful tool when working with polymorphic code or when handling objects whose specific types may vary during program execution. As a method of the Object class, GetType() can be applied to any object instance, providing a valuable mechanism for runtime type introspection and enhancing the flexibility and adaptability of your code.

The typeof operator is used when you want to obtain the type of a particular entity at compile time, which includes types known during compile-time or generic type parameters. The operand for typeof must be the name of a type or a type parameter, and it cannot be a variable or any runtime entity. The result of the typeof operator is calculated during compilation, and it provides access to type information that remains constant throughout the program's execution.

On the other hand, the GetType() method is called on individual objects at runtime to retrieve the execution-time type of the object. Unlike typeof, GetType() allows you to get the type dynamically based on the specific instance at runtime. It returns the actual runtime type of the object, which can be different from its compile-time type, particularly when dealing with polymorphism and inheritance.

In both cases the result is an object of the type System.Type containing meta-information on a type.

Example:
using System; namespace ConsoleApplication1 { class Car { } class Ford : Car { } class Program { static Car newCar() { return new Ford(); } static void Main(string[] args) { Car c = newCar(); Console.WriteLine(typeof(Car)); //Output : CAR Console.WriteLine(c.GetType()); //Output : FORD Console.ReadKey(); } } }

In the above example, within the Main() method, you are dealing with instances of type Car; so, if you care about the declared type, you would use typeof(Car). However, the newCar() method actually returns an instance of a derived class, Ford, despite declaring the base class as the return type. If you want to find out about this runtime type, call GetType on the returned instance.

GetType and TypeOf confusion

typeof vs Object.GetType() performance

From the above example, we should clear about the typeof operator is used when you want to get the Type instance representing a specific type. GetType() method gives the runtime type of the object on which it is called, which may be different from the declared type.