1.

Typeof() vs GetType() in C#

Answer»

The major difference between Typeof() and GETTYPE() is that while Typeof() obtains the type based on the class, GetType() obtains the type based on the OBJECT. DETAILS about both of them in C# are given as follows:

  • Typeof()

The Typeof() method is used to get the System.Type object for a given type. Also, this method can be used on open generic types but it cannot be overloaded.

A program that DEMONSTRATES the Typeof() method in C# is given as follows:

using System; using System.IO; class Demo {    public static void Main()    {        Console.WriteLine(typeof(int));        Console.WriteLine(typeof(char));        Console.WriteLine(typeof(double));        Console.WriteLine(typeof(int[]));        Console.WriteLine(typeof(Array));        Console.WriteLine(typeof(Stream));        Console.WriteLine(typeof(TextWriter));    } }

The output of the above program is as follows:

System.Int32 System.Char System.Double System.Int32[] System.Array System.IO.Stream System.IO.TextWriter
  • GetType()

The GetType() method obtains the type of the current object of the class. A program that demonstrates the GetType() method in C# is given as follows:

using System; class Animal { } class Mammal : Animal { } class Human : Mammal { } class Demo {    static void Main()    {        Animal obj1 = new Animal();        Animal obj2 = new Mammal();        Animal obj3 = new Human();        Console.WriteLine(obj1.GetType());        Console.WriteLine(obj2.GetType());        Console.WriteLine(obj3.GetType());    } }

The output of the above program is as follows:

Animal Mammal Human


Discussion

No Comment Found