whats the differece between:
((TextBox)(e.TabPage.Container)).Text
(e.TabPage.Control as RichTextBox).Text
Printable View
whats the differece between:
((TextBox)(e.TabPage.Container)).Text
(e.TabPage.Control as RichTextBox).Text
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.
hmm so which one should i use?!
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.
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..:rolleyes:Quote:
Or not, because you then might get a NullPointerException instead of a InvalidCastException, which tells you less about the source of the problem.
Code:BaseClass b = SomeClass as BaseClass;
if(b != null)
Console.WriteLine("Not Null...");
Yeah, of course, but that doesn't necessarily make it easier to use.
It's a cleaner solution than relying on a try...catch block....
That's why they included it into the language.
Also note that you may use "as" only for reference types like strings, objects, etc. not value types such as int, Color, etc...