c# Casting v As operator
-
PIEBALDconsult wrote:
what are you people doing?
SomeType obj = (SomeType)BloatedUglyUnreadableFrameworkFactory.CreateObject(someXMLStringThatIHopeWorksSometimesButNeverKnowForSure);
That deserves to blow up. What do you do once you've determined that it didn't work? Don't you just throw an Exception anyway?
-
Yes that's the specification of the behavior, but not how it's implemented.
Eric Lippert wrote:
The specification is clear on this point;
as
(in the non-dynamic case) is defined as a syntactic sugar foris
. However, in practice the CLR provides us instructionisinst
, which ironically acts likeas
. Therefore we have an instruction which implements the semantics ofas
pretty well, from which we can build an implementation ofis
. In short, de jureis
isis
, andas
is asis
is, but de factois
isas
andas
isisinst
.http://blogs.msdn.com/b/ericlippert/archive/2010/09/16/is-is-as-or-is-as-is.aspx[^]
I'll code to the spec and assume hope they'll fix the implementation.
-
For those using c#, what do you prefer? A.
SomeObject obj = (SomeObject) e;
or B.
SomeObject obj = e as SomeObject;
www.software-kinetics.co.uk Wear a hard hat it's under construction
b. it's better, because if the cast is wrong, the member would be null ... so you don't have to surround your code with a "try {} catch {}" every few lines. :)
-
For those using c#, what do you prefer? A.
SomeObject obj = (SomeObject) e;
or B.
SomeObject obj = e as SomeObject;
www.software-kinetics.co.uk Wear a hard hat it's under construction
For reference Type, should have to use 'As' operator because of if casting is not compatible with target Object then it return null while 'Casting' throws an exception. For Value Type,'As' operator doesnot work.
-
For those using c#, what do you prefer? A.
SomeObject obj = (SomeObject) e;
or B.
SomeObject obj = e as SomeObject;
www.software-kinetics.co.uk Wear a hard hat it's under construction
-
For those using c#, what do you prefer? A.
SomeObject obj = (SomeObject) e;
or B.
SomeObject obj = e as SomeObject;
www.software-kinetics.co.uk Wear a hard hat it's under construction
I guess this wasn't a serious question, but just in case somebody who doesn't know looks in, I prefer b as it won't throw an exception if the conversion is not possible, but rather will return a null. According to MSDN[^] it's equivalent to this:
expression is type ? (type)expression : (type)null
butexpression
is only evaluated once. -
I guess this wasn't a serious question, but just in case somebody who doesn't know looks in, I prefer b as it won't throw an exception if the conversion is not possible, but rather will return a null. According to MSDN[^] it's equivalent to this:
expression is type ? (type)expression : (type)null
butexpression
is only evaluated once.I suppose my argument on that, is the programmer should know if conversion will take place or not, than letting the code take control.
www.software-kinetics.co.uk Wear a hard hat it's under construction
-
Splitting hairs :)
www.software-kinetics.co.uk Wear a hard hat it's under construction
Not really, C style casts are not recommended in C++ last I checked. Its preferred to use the C++ casts
dynamic_cast<T>(x)
,static_cast<T>(x)
,reinterpret_Cast<T>(x)
andconst_cast<T>(x)
as they make the intention more explicit. See : Stroustrup[^] -
Not really, C style casts are not recommended in C++ last I checked. Its preferred to use the C++ casts
dynamic_cast<T>(x)
,static_cast<T>(x)
,reinterpret_Cast<T>(x)
andconst_cast<T>(x)
as they make the intention more explicit. See : Stroustrup[^]The final years of coding MFC, I was using the xxx_cast operators religously.
www.software-kinetics.co.uk Wear a hard hat it's under construction
-
I prefer
as
because it is safer:expression as type
is equivalent to:
expression is type ? (type)expression : (type)null
When you use casting you can get
StoopidTypeException
.
Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett
I fail to see why that is safer. In case (a), an exception can be raised if expression is of the wrong type. That seems entirely appropriate. In case (b), if an expression of the wrong type is supplied, the result is null. If a programmer fails to check this, the result is an exception anyway. There's a place for both of them. I generally prefer errors to generate exceptions early - i.e. at the cast, rather than the point of usage. So, if I really expect the result to be of a given type I use the former. If I'm using the cast as a shorthand for checking the type is OK, then casting, I prefer the latter.
-
I'll code to the spec and assume hope they'll fix the implementation.
There is always a difference between spec and implementation. A language spec is designed to specify what an implementer must achieve - how they achieve it is up to them. For example, nothing in the C++ spec specifies vtables are required to implement virtual functions. The vast majority of compilers implement them that way, but a vendor is free to do things some other way.
-
Wrong - a is C-style casting, not C++
No the first is compile time and the second is run time. 'as' keyword is used to RTTI
-
It depends. (A) will throw if the cast fails while (B) will evaluate to
null
if the cast fails. I use both depending on how I intend to handle the casting failure. /raviMy new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com
There's a little more than that. See here: what-s-the-difference-between-as-and-cast-operators[^]
Eusebiu
-
For those using c#, what do you prefer? A.
SomeObject obj = (SomeObject) e;
or B.
SomeObject obj = e as SomeObject;
www.software-kinetics.co.uk Wear a hard hat it's under construction
'B' is better, Because use of 'as' operator does not throw exception if casting is not successful where as 'A' will throw exception in case casting fails.
-
For those using c#, what do you prefer? A.
SomeObject obj = (SomeObject) e;
or B.
SomeObject obj = e as SomeObject;
www.software-kinetics.co.uk Wear a hard hat it's under construction
Often I see the 'as' keyword misused in a way that it hides the cause of a
NullReferenceException
. For example, take a look at this crummy code:((foo as (Light)).SwitchOn(); // bad
If
foo
is not aLight
, then aNullReferenceException
is raised. But iffoo
wasnull
to begin with, then aNullReferenceException
is also raised. In either case, we can’t be certain if it is one or the other. When the ‘as’ is replaced by a direct cast, anInvalidCastException
is raised whenfoo
is not aLight
; allowing us to distinguish between the two situations:((Light)foo).SwitchOn(); // better
Sometimes, therefore, the choice to use 'as' or a direct cast isn’t a choice at all.
Daniel Vaughan Twitter | Blog | Microsoft MVP | Projects: Calcium SDK, Clog | LinkedIn
-
For those using c#, what do you prefer? A.
SomeObject obj = (SomeObject) e;
or B.
SomeObject obj = e as SomeObject;
www.software-kinetics.co.uk Wear a hard hat it's under construction
I use this :
if(e is SomeObject)
{
SomeObject obj = (SomeObject)e;
} -
The final years of coding MFC, I was using the xxx_cast operators religously.
www.software-kinetics.co.uk Wear a hard hat it's under construction
That makes a change. It seems most C++ programmers are either unaware of them, or just lazy typists. A good sign of this is that my response above seems to have been downvoted for some reason (not that I care - I find the obsession with ratings here a bit odd). Maybe my knowledge of C++ is incomplete, but I assume Stroustrup knew his intention on introducing that feature.
-
That's their problem.
Maybe, but its generally considered good form if coding an exposed API to be defensive wrt such fails by the developer using your API. Naturally, there are exceptions euch as performance critical code, where the costs of such checks outweigh the benefits of improved diagnostics. My approach is that if code is called only internally (ie. by developers working on our products), it may be safe to avoid such checks. If called externally (by third party developers), it rarely is.
-
For those using c#, what do you prefer? A.
SomeObject obj = (SomeObject) e;
or B.
SomeObject obj = e as SomeObject;
www.software-kinetics.co.uk Wear a hard hat it's under construction
Norm .net wrote:
For those using c#, what do you prefer?
A.SomeObject obj = (SomeObject) e;
or
B.SomeObject obj = e as SomeObject;
What about secret option C. use the correct one for the circumstances. While you might have been interested in which of the two we prefer, thats like asking which do you prefer: A. for B. return You might have a preference, but they aren't interchangeable. You should use A if the object has to be of the correct type. You will get an exception and your exception processing will clean up for you as best as it can. You should use B if you are expecting different types. You get a null so you try the next type. This isn't very OO but it can be useful for optimising. The code will almost always be more procedural, so you have to be careful not to over complicate it. Trying to stop exceptions being thrown at all costs is like using ON ERROR RESUME NEXT in VB. Unless you know exactly how to process an exception you shouldn't try to catch it or defend against it.
-
No, because the two are not equivalent (see other posts below).
viaducting wrote:
No, because the two are not equivalent (see other posts below).
Exactly. I believe "as" returns null if the attempt to cast was unsuccessful, while casting will produce an exception. So, for testing if the cast was successful or not: With casting, you'd need a try/catch block. But with "as" you could just test the result if it's null or not, with an if statement. (<-- arguably less code/more readable).