Mark Rae said:
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.