.Net Type Saftey violation? or just confusion...

  • Thread starter Thread starter Andy Read
  • Start date Start date
A

Andy Read

Greetings all,

I'm currently reading the excellent applied .Net Framework programming
by Jeffrey Ritcher. In the Type Fundamentals chapter a brief description of
the System.Object methods is given.

Against the GetType member it says: This method is nonvirtual preventing
classes from overriding the method and lying about its type, violating type
safety.

This all seems to make prefect sense. But... you could 'Shadow' the GetType
function in a class and return a completely different type. Does this not
violate type safety? If not could someone please explain?

Many Thanks

Andy Read.
 
I'm currently reading the excellent applied .Net Framework programming
by Jeffrey Ritcher. In the Type Fundamentals chapter a brief description of
the System.Object methods is given.

Against the GetType member it says: This method is nonvirtual preventing
classes from overriding the method and lying about its type, violating type
safety.

This all seems to make prefect sense. But... you could 'Shadow' the GetType
function in a class and return a completely different type. Does this not
violate type safety? If not could someone please explain?

You could declare a new method with the same signature as GetType, but it
would only ever get called when you did:

MyType bleh = new MyType();
Type t = bleh.GetType();

If you were to do the following:

object bleh = new MyType();
Type t = bleh.GetType();

The GetType method inherited from object will be called.

If you have a variable declared as MyType, it's fairly obvious what type it
really is, and it doesn't really matter if you've hidden the GetType that was
inherited from object. The real GetType method will be called when an instance
of your class is referenced as an object.
 
Back
Top