Type Checking in C# and VB.NET

Type Checking in C# and VB.NET

Hello Readers,

Type Checking in C# and VB.NET

Type Checking in programming languages is a program analysis that verifies something about the types that are used in the program. Let’s find out how type checking in c# and vb.net is done?

Type checking in C# and VB.NET #csharp #vbdotnet #programming #microsoft Click To Tweet

Type Checking in C#

In C#, you can use typeof operator and GetType() method to get the types.

  • typeof is an operator to obtain a type known at compile-time (or at least a generic type parameter).
  • GetType() is a method you call on individual objects, to get the execution-time type of the object.

This below condition is true if obj is exactly of type Employee. If obj derives from Employee, the if condition will be false.

The typeof operator in C# returns an instance of the System.Type class containing type declarations of the type you pass to it.

The VB equivalent of the C# typeof operator is the GetType operator.

Type Checking in VB.NET

In VB.NET, you need to use the GetType() method to retrieve the type of an instance of an object, and the GetType operator to retrieve the type of another known type.

You can also use the TypeOf operator instead of the GetType() method. Note that this tests if your object is compatible with the given type, not whether it’s the same type.

Quick Tip for VB.NET

Just a quick tip regarding the way to check the type of objects in VB.NET.

Have a look at the below code snippet:

In this case, it’s okay because Me cannot be null, but if you are checking some other object like this:

If obj happens to be null then you’ll get a NullReferenceException.

A better way to check the type is like this:

This won’t be throwing an exception, even if the obj is null.

The above example demonstrates just two ways to do something, However, one is more prone to error than the other. Hence, the latter way turns out to be a better way to do it.

Hope you understood the difference between typeof and GetType in C# as well as in VB.NET.

Points to Remember

  • Both typeof and GetType gets the type. However, the difference lies in from where the information is extracted.
  • typeof gets the type from a class while GetType gets it from an object.

What do you think?

Dear Reader,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

Happy Coding!