Why casting so often in MSDN samples?

  • Thread starter Thread starter KevinG
  • Start date Start date
K

KevinG

Hi,

I am new to .NET and the .NET CF but have started to play with it
lately. One thing that has puzzled me is the amount of casting going
on in the MSDN samples, for example in the code on the HTTPWebRequest
help page we have:

VB
....
Dim myHttpWebRequest1 As HttpWebRequest =
CType(WebRequest.Create(myUri), HttpWebRequest)
....

and C#
....
HttpWebRequest myHttpWebRequest1=(HttpWebRequest)
WebRequest.Create(myUri);
....

Are the above casts really necessary? I would have thought they were
not. They tend to make the code look very ungainly, especially in VB!
The code compiles fine without them. I would like to leave them out
but I am worried they might be require for some strange reason!


Thanks for reading,

Kevin.
 
KevinG said:
and C#
...
HttpWebRequest myHttpWebRequest1=(HttpWebRequest)
WebRequest.Create(myUri);
...

Are the above casts really necessary? I would have thought they were
not. They tend to make the code look very ungainly, especially in VB!
The code compiles fine without them.

This is simply not so. Implicit upcast is not possible. Only downcasting can
happen that way. The descendant class has to be explicitly cast to the
antecedent
 
Why is casting unsightly? It offers the reader a much better insight into
what the author intended, plus it's very often necessary. Implicit casting
is, IMHO, dangerous simply because it's not explicit and occasionally will
not do what you thought it would.

-Chris
 
Explicit Casting also generally improves performance as it allows for more
compile-time optimizations, as well as making coding easier in terms of
intellisense etc.

-Alex Clark
 
In VB. In C# you have strict typing requirements, so without typecasting
code simply won't compile
 
Thanks to all for the replies & info!

I missed the point that in the sample we were moving from WebRequest
to HttpWebRequest and so an implicit cast is necessary.

KevinG
 
Back
Top