views:

92

answers:

2

code sample taken from MSDN

public class Test {
public static void Main() {
  MyBaseClass myBase = new MyBaseClass();
  MyDerivedClass myDerived = new MyDerivedClass();
  object o = myDerived;
  MyBaseClass b = myDerived;

  Console.WriteLine("mybase: Type is {0}", myBase.GetType());
  Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
  Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
  Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());   }}

/*
This code produces the following output.
mybase: Type is MyBaseClass
myDerived: Type is MyDerivedClass
object o = myDerived: Type is MyDerivedClass
MyBaseClass b = myDerived: Type is MyDerivedClass 
*/

So would it be logical to make GetType() virtual at least it works as virtual? Can anybody explaine that? And other question Is any other methods in NET framework which have behaviour alike GetType?

+9  A: 

because .Net framework does not want you to override the GetType() method and spoof about the type.

assume you can override the method what else would you want it to do other than returning the type of the instance. and when you override the method for each of your classes to return the type of the instance, won't you violate DRY then.

this. __curious_geek
and reasonably so!
David Hedlund
yes. you're right. but you may overload this public method in derived class ))
Arseny
@Arseny: Then it's not the same as GetType() as defined on the Object type.
this. __curious_geek
+2  A: 

GetType returns the actual Type of the object. This allows us to know what object we really got passed to 'our' function. Many methods of the framework need this to determine their own functionality - in most cases to get the Attributes of this class. If the Framework would loose the possibility to determine the real type of an object, the object would loose this type as well.

If you like to know the type used within your method scope - the type you declared or was picked by the compiler - you can add a pretty simple extension method:

public static Type GetCurrentType<T>(this T obj)
{
    return typeof(T);
}

public static void Main()
{
  MyBaseClass myBase = new MyBaseClass();
  MyDerivedClass myDerived = new MyDerivedClass();
  object o = myDerived;
  MyBaseClass b = myDerived;

  Console.WriteLine("mybase: Type is {0}", myBase.GetCurrentType());
  Console.WriteLine("myDerived: Type is {0}", myDerived.GetCurrentType());
  Console.WriteLine("object o = myDerived: Type is {0}", o.GetCurrentType());
  Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetCurrentType());
}

/*
This code produces the following output.
mybase: Type is ValidatorTest.MyBaseClass
myDerived: Type is ValidatorTest.MyDerivedClass
object o = myDerived: Type is System.Object
MyBaseClass b = myDerived: Type is ValidatorTest.MyBaseClass
*/
Kelon