3.2.9 How to Use GetType

Many times when writing code there are instances where we will want to ensure that an object is a certain type of thing. There is a method in the Object class called GetType that allows us to return the custom type of a particular custom class. This article will cover how to leverage GetType in tandem with typeof to ensure an object in question is the correct type.


Below we have a block of code that has a Boss type finding the name of an Employee in their list of employees to attend a meeting. The FindEmployee method loops through the list and compares each employee with a name passed in and if they are found, returns the Employee object.

But what if the Boss is in a hurry and doesn't care about who the person is in particular, they just want to have a type of Employee attend the meeting? What we can do is use a combination of GetType and typeof to find a type of Employee in the list without needing to care about who they are.


The GetType method is a method that "lives" in the Object class. Since all classes inherit from the Object class we have access to it. We have seen this before when Intellisense has given it to us as a member we could invoke, but we've never used it.

If we F12 on GetType we will see that it is in the Object class and returns a Type; this means it will return whatever the Type of the object is that we are calling this method on.

So let's test this:

We can see that the local type variable of Type Type (yeah, it's a mouthful) is Custodian.


Now we can use that type to ensure that an object is a Type that we want. This can't be done, however without using another keyword: typeof. The keyword typeof belongs to the System, which we won't dive into, but we will use it by using the notation typeof(ClassName). When we test this it looks like:

Note that the Value of both the typeof and GetType are identical. This is good new since we want to compare them. To do this we're going to replace the string parameter in the FindEmployee method with a Type parameter and then pass in the Type we want to find as an argument using typeof and change the parameter reference.

We have an issue, though. We are trying to compare a Type with a string.

So let's use GetType to get the Type of the Employee object instead.

Now since the type parameter matches the Employee object's(e) Type the employee variable will be assigned to the e object.

Note that now, because Oscar was the first Employee in the list that was a Custodian type, Oscar will returned instead of Kevin.