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?
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.
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.
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.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With