Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use () vs. 'as' to change type? [duplicate]

Possible Duplicate:
Casting: (NewType) vs. Object as NewType
Casting vs using the 'as' keyword in the CLR

//var gridView = (gridViewRow.NamingContainer as GridView); <-- works too
var gridView = (GridView)gridViewRow.NamingContainer;

My incomplete understanding of this is using as keyword can give null when using a cast () will throw an exception. My goal is to be able to ask myself "which way should I cast?" and know how to answer it.

like image 566
Aaron Anodide Avatar asked Dec 02 '11 19:12

Aaron Anodide


3 Answers

It depends, but basically:

If you know and can guarantee that the object is the type you think it is then use ().

If there's a possibility that it could be something else then use as and check for null. In this case you'd have:

var realThing = someObject as MyClass;
if (realThing != null)
{
    ....
}

You can use is to guard the () which would result in:

if (someObject is MyClass)
{
    var realThing = (MyClass)someObject;
    ....
}

But this results in two conversions, rather than the one of as or the straight () cast.

This is where the "it depends" comes in. You'd have to decide on a case by case basis which was more appropriate. You might have coding standards to adhere to as well.

like image 170
ChrisF Avatar answered Oct 10 '22 07:10

ChrisF


The question is more of

How do I want my code to deal with a dynamic cast failure?

If you have an implicit / explicit contract that gridViewRow.NamingConainer is in fact a GridView then an () cast is appropriate. If the type is not a GridView it's violated a contract, an exception is thrown and the error will be apparent. However if it's possible that it's not a GridView and you want to proactively handle the case then as is appropriate.

In this case it looks like you do have an implicit contract that it is a GridView and hence I would continue to use (). If you went with as and the contract was broken you'd end up with a NullReferenceException which is not actually the problem. The problem is the type wasn't a GridView as expected and hence InvalidCastException is much more appropriate

like image 38
JaredPar Avatar answered Oct 10 '22 07:10

JaredPar


The C# Frequently Asked Questions blog covers this in What's the difference between cast syntax and using the as operator?. There is a discussion of the caveats from Andrew Arnott that you might be interested in too.

like image 28
Brian Lyttle Avatar answered Oct 10 '22 08:10

Brian Lyttle