DirectCast vs CType

Good stuff, thanks PD! To review... dont use CType because its VB6 legacy reach-back (as us net-admins would say :)). For my traditional C# casting I need to:

Dim x as ObjectType
x = DirectCast(y, ObjectType)
x.DoWhatever()

C# equiv (why I really like C#):
((ObjectType)x).DoWhatever();

And if I need numbers
Dim i as Integer = Integer.Parse(str)
-or-
Dim i as Interger = Convert.ToInt32(str)

Is one preferred over the other?
 
Hmm... didnt know CType() is for Legacy Code. (Erases CType from the keywords list).
((ObjectType)x).DoWhatever();
That single line of code looks fairly hard to read (to me anyway). But the C# equivalent to the top line :
Code:
Dim x as ObjectType
x = DirectCast(y, ObjectType)
x.DoWhatever()
is:
Code:
ObjectType x;
x = (ObjectType) y;
x.DoWhatever();
And the VB equivalent to:
Code:
((ObjectType)x).DoWhatever();
is
Code:
DirectCast(x, ObjectType).DoWhatever()
Just as difficult to read as that C# line of code. :(
You should try to keep things simple instead of having it crumpled together on one line.

If you were converting a string to an integer, I would say to use Integer.Parse, but thats just my opinion.
 
Code:
DirectCast(x, ObjectType).DoWhatever()
Just as difficult to read as that C# line of code.
I actually found that very simple to read, a lot cleaner than 3 lines of code; direct and to the point. Maybe its because Im use to do it that way, which from what Ive seen in code examples is the preferred C# way, thats how I got into doing it. But IMHO (in my humble opinion) I think thats easier (one line crumpled together instead of three lines). Guess its really semantics, but Im curious as to others thoughts on what coding style they prefer and if anyone knows what M$ recommends. Thanks for the help though, I did learn something from it.
 
Back
Top