Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using "as" in C# a safe way of casting?

Tags:

c#

casting

I am wondering if using the keyword "as" in the following code is a safe way (i.e. won't blow up) of casting in C#:

public void abc(ref Object dataSource) {     DataTable table = dataSource as DataTable; } 

Is there a safer way of casting?

like image 860
developer Avatar asked Jun 17 '11 16:06

developer


People also ask

Is Vs as in C#?

The is operator returns true if the given object is of the same type, whereas the as operator returns the object when they are compatible with the given type. The is operator returns false if the given object is not of the same type, whereas the as operator returns null if the conversion is not possible.

What is using () in C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

What is an alias in C#?

Introduction. Namespaces in C# serve two main purposes: to organize classes and functionality and to control the scope of classes and methods. Type aliasing is a little known feature for C# and it comes in handy when you would like to alias a specific method or class from a namespace for the sake of clarity.

What is new in C sharp?

Use the new keyword to create an instance of the array. The new operator is used to create an object or instantiate an object. Here in the example an object is created for the class using the new.


1 Answers

It won't blow up... but that doesn't necessarily mean it's safe.

Typically when I use a cast for a reference conversion, it's because I really, really think that the execution-time type is the one I'm specifying. If it's not, that indicates a bug in my code - and I'd rather that manifested itself as an exception.

If you've got bad data in your system, then continuing as if everything was fine is the dangerous path, not the safe path. That's the way that as will take you, whereas a cast would throw an InvalidCastException, aborting whatever you're doing before you get the chance to cause mayhem with the bad data.

as is good if it's valid for the object not to be of the given type - if it doesn't indicate a bug. You almost always see the pattern of:

Foo x = y as Foo; if (x != null) {     ... } 

See MSDN for more details about what as does.

Note also that you probably don't want to use ref in your method. See my article on parameter passing for more details. Most of the time if I see people using ref a lot, it's because they don't understand what it really means :)

like image 158
Jon Skeet Avatar answered Sep 21 '22 08:09

Jon Skeet