Can someone explain this simple code? First time I see it in a C# example
Button btn = sender as Button;
if (btn != null)
Printable View
Can someone explain this simple code? First time I see it in a C# example
Button btn = sender as Button;
if (btn != null)
It's just converting from one type to another compatible type. The result is basically the same as:but the implementation is not quite the same. Check it out in the help, which is pretty much my first advice for everything. Just set the Filter to C# and search for "as" (without quotes).Code:Button btn;
try
{
btn = (Button)sender;
}
catch (Exception ex)
{
btn = null;
}
it doens't use a catch block
it's more like this, I cant remember EXACTLY, but it's very close:
it's good cuz it reduces some code writing. Also the "is" operator lets you check types (it, that woudl be the same as doing if (btn.GetType() == typeof(Button))Code:btn = (sender is Button?
(Button)sender :
null
catch block would be inefficient:D
I only used that as an illustration in easily understandable terms. :) I did state that the implementation is not the same. The help topic uses the ternary if-else operator as an illustration also, because that is not the same either because the expression being converted is only evaluated once when using "as". Basically, it is an operator and it can't necessarily be equated to any C# code because it is part of the language itself.
Gotcha with your first post jmcilhinney...could not make it more clear. :)
Thanks for the replies...
yeah I didnt read your post properlyQuote:
Originally Posted by jmcilhinney
but bleh MSDN says they are the same
The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:
expression as type
is equivalent to:
expression is type ? (type)expression : (type)null
:afrog:
You omitted the line that follows that:which implies that, as for my example, the result is the same but the route taken to get there is different.Quote:
except that expression is evaluated only once.
I see, I did miss it:afrog: thanksQuote:
Originally Posted by jmcilhinney
and cheer up:D:D:D
You can consider me suitably cheery. :D There was a lack of smilies in my previous post but I was still a'smlin'. :) I just want to be cheerful and right. :blush:
heheheheQuote:
Originally Posted by jmcilhinney
perhaps I use too many smilies:D
umm I'm stretching this thread a bit, but do you know if a similar statement exists in vb.net or not?
Not that I'm aware of, but then I don't know everything, no matter how hard I try to pretend I do. :)