J.V.
Try casting into a
user-defined class which is modified as MustInherit(if you are VB
oriented) and obtain it through inheritance into another class. Then,
try DiectCast to cast a normal class to that of the MustInherit class
and it will work till the exception is thrown at runtime. Whereas, in
the same scenario, CType will show you an error before compile time. I
am of course talking in terms of VS.Net Ide.
That made absolutely no sense! :-(
Please use either proper OO terms or proper VB.NET terms. Or take 2 minutes
to type in an example of what you are attempting to state, it would help.
Do you mean:
1. cast an abstract class (MustInherit) into a derived class (inherited)
2. cast a derived class into a base class
3. cast Class1 to Class2 where Class1 & Class2 are not related
4. convert Class1 to Class2 where Class1 & Class2 are not related
First remember that DirectCast is the Cast operator, while CType is the
Conversion operator that will do a Cast if the cast is allowed. Also
remember that Casting & Converting are separate (although closely related)
operations.
Looking at each of the above:
1. Casting an base (abstract or not) class to a derived class there is no
difference between CType & DirectCast as I stated. This is normal usage for
DirectCast. In this case derived class also includes implemented interfaces.
2. Casting a derived class into a base again there no difference. This cast
is actually implicit so CType or DirectCast is not needed.
3. Casting Class1 to Class2 is simply not allowed, you will get a runtime
error.
4. However! Conversion is allowed, if there is a conversion defined between
Class1 & Class2! Again If a conversion is defined is the key word here!
Today the conversions are defined for the "built-in" types. For user types
you will need to wait for Whidbey to get conversion operators, hence today
Convert Type will give an error when you attempt to Convert Class1 to
Class2, however tomorrow if the conversion is defined it will convert the
type! Conceptionally a conversion to String is defined for all types as
System.Object has the ToString method however I don't think, nor would I
expect, CType will recognize this.
(Hint at) Overloading Operator CType in Whidbey:
http://blogs.gotdotnet.com/cambecc/permalink.aspx/5de5a161-9150-4237-a751-127195cceeab
Whidbey also promises to give us TryCast which is a variation of DirectCast:
http://www.panopticoncentral.net/PermaLink.aspx/0d6ba439-8126-427e-952e-3f5fbba33904
By the way, since you are a MVP-Outlook, I am asking this question. When
I try to switch my identity in Outlook Express 5.0 after having added a
new identity, why does the switch not take place ?
Yes I am an Outlook MVP, I am not however an Outlook Express MVP.
Hope this helps
Jay