tag:blogger.com,1999:blog-3573606178901893990.post7029415348536730753..comments2024-01-28T01:30:51.917-08:00Comments on The Monkey's Grinder: Casting CallUnknownnoreply@blogger.comBlogger3125tag:blogger.com,1999:blog-3573606178901893990.post-47278023622275525402009-07-17T10:56:12.474-07:002009-07-17T10:56:12.474-07:00Using "as" and checking for null is no m...Using "as" and checking for null <a href="http://higherlogics.blogspot.com/2009/02/cost-of-type-tests-and-casts-in-c.html" rel="nofollow">is no more efficient than than checking the type via "is" and then casting using "as"</a>.<br /><br />Furthermore, it's less safe since you have a potentially null reference available in the outer scope which may be inadvertently dereferenced elsewhere. I cringe whenever it, and I really hope this bad advice just dies already.Sandro Magihttps://www.blogger.com/profile/05446177882449578817noreply@blogger.comtag:blogger.com,1999:blog-3573606178901893990.post-72108800608969857252009-07-17T10:24:39.770-07:002009-07-17T10:24:39.770-07:00I was working on a Gendarme rule to detect these b...I was working on a Gendarme rule to detect these bad cases. I wrote a first version, but lazyness made me not to insist on it (I got some reviews on the gendarme list, but never got back to them; so you're more than welcome if you want to step up).knoctehttps://www.blogger.com/profile/00267496347097861887noreply@blogger.comtag:blogger.com,1999:blog-3573606178901893990.post-10650673538072633832009-07-17T09:38:00.130-07:002009-07-17T09:38:00.130-07:00Two more for you
1. You can use 'as' with...Two more for you<br /><br />1. You can use 'as' with nullable types, thus allowing use of value types without an 'is'/cast combination:<br /><br />var a = o as int?;<br />if (a.HasValue) {...}<br /><br />2. foreach() implicitly inserts a cast operation to the control variable type. This is most noticeable when using 1.0 collections:<br /><br />ArrayList strings = GetStrings();<br />foreach (var s in strings) {/* s is an Object! */}<br /><br />foreach (string s in strings) {<br /> /* s is string, but you may get an <br /> InvalidCastException if the cast fails */<br />}Jonathan Pryorhttps://www.blogger.com/profile/14099006045921906356noreply@blogger.com