|
-
Mar 29th, 2003, 03:07 PM
#1
Thread Starter
yay gay
casting difference?
whats the differece between:
((TextBox)(e.TabPage.Container)).Text
(e.TabPage.Control as RichTextBox).Text
\m/  \m/
-
Mar 29th, 2003, 03:35 PM
#2
PowerPoster
The first cast is using an explicit cast and will throw an exception if an invalid cast is attempted. Using the 'as' keyword, it will return a null reference if an invalid cast is attempted, otherwise, will return the object reference.
-
Mar 29th, 2003, 04:56 PM
#3
Thread Starter
yay gay
hmm so which one should i use?!
\m/  \m/
-
Mar 29th, 2003, 10:18 PM
#4
PowerPoster
It depends on the situation in which you plan on casting...
If you do not know ahead of time the exact type(s) of objects your are dealing with, it would be safe to use the 'as' construct.
-
Mar 30th, 2003, 01:01 PM
#5
Or not, because you then might get a NullPointerException instead of a InvalidCastException, which tells you less about the source of the problem.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Mar 30th, 2003, 04:14 PM
#6
PowerPoster
Or not, because you then might get a NullPointerException instead of a InvalidCastException, which tells you less about the source of the problem.
I assumed from my explanation that he would check after the cast for a null reference..
Code:
BaseClass b = SomeClass as BaseClass;
if(b != null)
Console.WriteLine("Not Null...");
-
Mar 31st, 2003, 10:10 AM
#7
Yeah, of course, but that doesn't necessarily make it easier to use.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Mar 31st, 2003, 11:47 AM
#8
PowerPoster
It's a cleaner solution than relying on a try...catch block....
That's why they included it into the language.
-
Mar 31st, 2003, 04:45 PM
#9
Also note that you may use "as" only for reference types like strings, objects, etc. not value types such as int, Color, etc...
Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|