c# Casting v As operator
-
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).
-
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
You are SO wrong! 1- 'As' works only with classes, it's like the dynamic_cast operator from C++, it returns null if the types do not match. 1- The static cast works both with classes and structs, but will throw an InvalidCastException if the types do not match. Hope it helps
Saludos!! ____Juan
-
That's their problem.
PIEBALDconsult wrote:
That's their problem.
If Only. Note, my two options allow for your point of view. If you want to you can use option 'a' for plug-in scenarios and let the exception bubble up till it's handled. The point I'm making is that the decision is more about communication with fellow coders than with the machine. The Compiler doesn't give a rats ass which you use. If you use the casting approach as the normal approach, it makes the alternative 'AS' approach stand out as something unusual. This *should* convey something to someone reading your code, even if that someone is you six months from now. The 'AS' approach with a check for NULL tells the reader that NULL in an occasionally expected value, not an exception. That's valuable info right there. The only thing I would advice against is using both methods interchangeably with no thought for why you use one in a given situation and not the other. -Richard
Hit any user to continue.
-
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 would prefer option B.
-
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).
Potential "invisible" bugs hard to debug if you forget to test "null value" after using AS operator. Personnaly, I prefer to have an exception, even if it's a little bit more code to handle it. If I forget the error handler, there is an immediate punishment :)
-
Sorry - wrong. The answer's a, because it's better.
"The difference between genius and stupidity is that genius has its limits." - Albert Einstein
"As far as we know, our computer has never had an undetected error." - Weisert
"If you are searching for perfection in others, then you seek disappointment. If you are seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010
-
Not your name, your sig:
W∴ Balboos wrote:
Possibly a font-problem on your end?
It looks roughly like: W**.'.** Balboos - the three punctuation-like characters being the HTML character code:& there4;
(space put in after & so it doesn't render)"The difference between genius and stupidity is that genius has its limits." - Albert Einstein
"As far as we know, our computer has never had an undetected error." - Weisert
"If you are searching for perfection in others, then you seek disappointment. If you are seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010
There's a lot of white space...
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
Oh - that white space. I happen to like separating the last line of text from the sig. In this case, I didn't put in CR's, but instead created a < div > - am not sure if that helps you. Esthetics. Beauty in the eye of the beholder. &etc.
"The difference between genius and stupidity is that genius has its limits." - Albert Einstein
"As far as we know, our computer has never had an undetected error." - Weisert
"If you are searching for perfection in others, then you seek disappointment. If you are seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010
-
Potential "invisible" bugs hard to debug if you forget to test "null value" after using AS operator. Personnaly, I prefer to have an exception, even if it's a little bit more code to handle it. If I forget the error handler, there is an immediate punishment :)
This is true, although you'd also get a visible (semi-)immediate null reference exception when you try to use anything from the object. Plus, I personally use "as" so often that either: a) I remember to test it -- equally as well as I'd remember to use a try/catch in the other scenario, or b) when I forget/get a null reference, I remember to include failed casting as the possible culprit when debugging. I think we agree that it boils down to a "personally, I ..." kind of thing. :)
-
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
If programming is used to express intent, then I use option A when I have no intent to check if the cast was successful; I use option B if I intend to check if the result of the cast is null.
-
This is true, although you'd also get a visible (semi-)immediate null reference exception when you try to use anything from the object. Plus, I personally use "as" so often that either: a) I remember to test it -- equally as well as I'd remember to use a try/catch in the other scenario, or b) when I forget/get a null reference, I remember to include failed casting as the possible culprit when debugging. I think we agree that it boils down to a "personally, I ..." kind of thing. :)
-
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 VB.NET users, the equivalent is: A.
Dim obj As SomeObject = CType(e, SomeObject)
or more accurately
Dim obj As SomeObject = DirectCast(e, SomeObject)
or B.
Dim obj As SomeObject = TryCast(e, SomeObject)
although VB.NET does not support SomeObject being a nullable value type. And FYI my answer is the same as most of the others, you use what is necessary depending upon the task at hand :-)
Regards, Mark Hurd, B.Sc.(Ma.) (Hons.)
-
This is true, although you'd also get a visible (semi-)immediate null reference exception when you try to use anything from the object. Plus, I personally use "as" so often that either: a) I remember to test it -- equally as well as I'd remember to use a try/catch in the other scenario, or b) when I forget/get a null reference, I remember to include failed casting as the possible culprit when debugging. I think we agree that it boils down to a "personally, I ..." kind of thing. :)
"you'd also get a visible (semi-)immediate null reference exception when you try to use anything from the object." The null reference exception could potentially happen a long time later in code far, far away from the original As. Depending entirely on how the As result is used, of course. Probably the better question is about the other developers that work on the code. Will they know to assume failed casting is a possiblity? What if they're preference is cast/catch? MS probably went too far in allowing there to be two different ways to do the same thing that behave differently. Sure its more convenient, but its also potentially confusing when there's multiple developers.
patbob
-
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
This is no questions of preference: 1. You can not use "as" on value types 2. For reference types you can use "as" or "cast" but with different behaviour. (returns null or exception) So it depends on the situation and the problem and NOT on your preference. Other commenters think that it depends on coding style (test for null or exception), but for me this is no question of style. I want an exception to occur only if something unexpected happen. If downstream the whole code would break if the object is null - I will use the pattern cast-try-catch. If beeing null won't break the code or can be expected I will use "as". So my point is: each of the possibilities to convert the type of an object is useful in different circumstances and these do not depend on my taste or style.