Mark Rae <ma**@mark-N-O-S-P-A-M-rae.co.uk> wrote:
"Ytram" <ma************@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
AAMOI, is there any difference between:
ToolStripButton t = sender as ToolStripButton;
and
ToolStripButton t = (ToolStripButton)sender;
Seems that the second example is used a lot more frequently e.g. on MSDN etc
than the first...
The latter throws an exception immediately if sender is neither null
nor a reference to an instance of ToolStipButton (or a descendent). (If
sender were declared to be a type which had a conversion to
ToolStripButton, it would also invoke that conversion).
The first *just* says "If sender is a reference to an instance of
ToolStripButton or a descendant, set t to the same value; otherwise set
t to null".
If you need to test first, it's cheaper to use the first form, as you
only end up casting internally once, so instead of:
if (sender is ToolStripButton)
{
ToolStripButton t = (ToolStripButton)sender;
...
}
you'd have:
ToolStripButton t = sender as ToolStripButton:
if (t != null)
{
....
}
If, however, it's a bug for sender to be anything other than a
ToolStripButton, I'd just cast.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too