What is the difference between typeof(), GetType() and IS in C# and VB.NET

What is the difference between typeof(), GetType() and is?

  • typeof() takes a type name specified at compile Time.
  • GetType() gets the Type of an Object at runtime
  • is returns true if an instance is in the inheritance tree. Since the is Keyword is casting the object, you should use it with care.
  • here is an example.

    class Employee { } 
    class Developer : Employee { }
    
    void PrintTypes(Employee e) { 
        print(e.GetType() == typeof(Employee)) // false 
        print(e is Employee)                   // true 
        print(e.GetType() == typeof(Developer))    // true
    }
    

    Please Share us:
    Please rate this snippet

    7 thoughts on “What is the difference between typeof(), GetType() and IS in C# and VB.NET

    Leave a Reply