I was wondering this as well, then I read John Gough's excellent "Compiling
for the .NET CLR" [1] and he answered the question.  The main problem is
with non-sealed classes and their subtypes.  Given that you can generate a
class at runtime, having all casts statically checked at compile-time would
be bad.

The text below has been snipped from his sample chapter (available online).

Consider this case:

<snip type="quote" author="John Gough">

public A a; // A is an interface type
public B b; // B is a class object type
...
a = (A) b; // assign value in b to a

In the corresponding example with class types, on page 62, the compiler was
able to statically check the relationship between the types A and B. In this
case things are not so simple.

If class B is statically known to implement interface A, then the assignment
is known to be correct. This follows since, even if the exact type of b is a
subtype of B, it will inherit the obligation to implement A. The problem
occurs if A and B are apparently unrelated. In the class object case we
could reject the code as certain to fail. However, in the case of
interfaces, if class B is not sealed, then the exact type of b might be some
subtype of B, validly implementing the interface A. Casts to interface types
are thus seldom able to be rejected at compile time and mostly remain as
runtime type checks in the IL.

</snip>

[1] http://www.pearsonptg.com/book_detail/0,3771,0130622966,00.html

-----Original Message-----
From: Nathan Rogers (Public Mail) [mailto:[EMAIL PROTECTED]]
Sent: Wednesday, May 01, 2002 5:48 PM
To: [EMAIL PROTECTED]
Subject: [ADVANCED-DOTNET] Keys in collections


System.Collections.Hashtable raises a runtime exception if you attempt
to do a lookup on a key that doesn't implement IComparable (which makes
sense).

But I'm not sure why the "key" parameter in this (and other key-based
collections) class' method delcarations is "object", rather than
"IComparable", which would mean this error could be caught at compile
time.  This seems to stem from the declarations in IDictionary

My first thought is that it was done to support the use of value types
as keys (because I wasn't sure if they could implement interfaces - they
can't in Java), but they can in the CLS successfully be cast to
IComparable and indeed the object browser shows that things like Int32
implement IComparable.

My second thought is that it was to support enumerable-only collections
(without any key based lookup).  Seems a little weak though.  Can anyone
see another reason or flaw in my thinking?

Cheers

Nath

You can read messages from the Advanced DOTNET archive, unsubscribe from
Advanced DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

You can read messages from the Advanced DOTNET archive, unsubscribe from Advanced 
DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to