.NET Array Dictionary List String 2D Async DataTable Dates DateTime Enum File For Foreach Format IEnumerable If IndexOf Lambda LINQ Parse Path Process Property Regex Replace Row Sort Split Static StringBuilder Substring Switch Tuple

GetType is a method on object. It provides a Type object, one that indicates the most derived type of the object instance. This program helps us understand the base class and derived class relationship.


Tip: Base classes are described with transitive closure. This affects the types allowed as variables. GetType returns a type pointer.

Example. First, this program uses the GetType method on a base type reference to more derived objects. It shows how transitive closure helps us understand how base classes relate to derived classes.

Here: The program shows that the GetType method returns the most derived object type of the instance.

C# program that uses GetType on base type instance

using System;

class A

class B : A

class C : B

class Program
    static void Main()
	A a1 = new A();
	A a2 = new B();
	A a3 = new C();




The class A is used as base class. The class B derives from class A. And the class C derives from class B. The Main entry point executes and creates an instance of each class, but stores the references in the A type variables.

Next: The GetType method returns the most derived type of the instances, not the type of the variable.

Discussion. Let's discuss the concept of transitive closure and how it applies to the class derivation system in the C# language and the example shown. The term "transitive closure" is a principle applied to the base class relationship.

As you traverse the derivation chain in the class hierarchy, each successive derived class points to the first base class. It also points to all other intermediate nodes. This is transitive closure.

And: This example shows how transitive closure applies when you assign a base class reference to a class derived over two levels (A to C).

Summary. We demonstrated the GetType method when used with derived and base classes in the C# language. Further, we described the relationship of base classes and derived classes in the mathematical principle of transitive closure.

Review: GetType accesses the actual type of the object instance. It does not report the base types or the variable type.