O'Reilly Forums: Keyword " As " Vs Round Brackets - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Keyword " As " Vs Round Brackets

#1 User is offline   pepita 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 19
  • Joined: 05-March 08

Posted 26 March 2011 - 11:42 AM

Second edition , pag.290 :

private void button1_Click(object sender, EventArgs e)
{
ScaryScary fingersTheClown = new ScaryScary(“big shoes”, 14);
FunnyFunny someFunnyClown = fingersTheClown;
IScaryClown someOtherScaryclown = someFunnyClown as ScaryScary;
someOtherScaryclown.Honk()
}
It works too this way , using a cast :

ScaryScary fingersTheClown = new ScaryScary("big shoes", 14);
FunnyFunny someFunnyClown = fingersTheClown;
((ScaryScary)someFunnyClown).Honk();

it works also in all the examples with the keyword "as".

Googling here and there , i found this explanation :
<< ...The as operator is similiar to a cast but on any conversion failure null is returned as oppose to raising an
exception...>>
Hope this entry could be of general interest
:rolleyes:
0

#2 User is offline   pepita 

  • Active Member
  • PipPip
  • Group: Members
  • Posts: 19
  • Joined: 05-March 08

Posted 28 March 2011 - 04:42 AM

Found another ( authoritative) explanation :

<< There will be times in C# when you write functions
that take object parameters because the framework defines the method signature for you.
You likely need to attempt to cast those objects
to other types, either classes or interfaces. You’ve got two choices: Use the as operator or force
the compiler to bend to your will using a cast. You
also have a defensive variant: You can test a conversion with is and then use as or casts to convert it.

The correct choice is to use the as operator whenever you can because it is safer than blindly casting
and is more efficient at runtime. The as and
is operators do not perform any user-defined conversions. They succeed only if the runtime type matches
the sought type; they never construct a
new object to satisfy a request.>>
0

#3 User is offline   Josh_T 

  • New Member
  • Pip
  • Group: Members
  • Posts: 3
  • Joined: 31-January 13

Posted 02 February 2013 - 06:05 AM

The best explanation was:
Using (Class)variableToCast throws and exception if it's unable to cast.
Using (variableToCast as Class) silently passes null if it's unable to cast.

Using the later version allows your code to handle the null value whereas the former forces you to either make sure your code is perfect or handle the exception in code. There are pro's and con's to each and you'll have to make up your mind as to which to use.

Read more here:
http://blog.nerdbank...-c-keyword.html
http://gen5.info/q/2...s-casting-in-c/
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users