By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,952 Members | 1,937 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,952 IT Pros & Developers. It's quick & easy.

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

P: n/a
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.
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
> 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.

--
Iain Simpson
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.