Difference between typeof and GetType()

Difference between typeof and GetType()

Apart from the obvious (i.e. typeof operates on a type whereas GetType operates on an object), the main thing to watch out for is that GetType returns the underlying type of the object, which may not be the same as the type of the reference to the object. For example:

    class Base { }
    class Derived : Base { }

    class Program
    {
        static void Main()
        {
            ShowType( new Derived() );
        }

        static void ShowType( Base b )
        {
            Console.WriteLine(typeof(Base));
            Console.WriteLine(b.GetType());
        }
    }

gives the following output:

    Base
    Derived

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.