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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
aswill take you, whereas a cast would throw anInvalidCastException, aborting whatever you’re doing before you get the chance to cause mayhem with the bad data.asis 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:See MSDN for more details about what
asdoes.Note also that you probably don’t want to use
refin your method. See my article on parameter passing for more details. Most of the time if I see people usingrefa lot, it’s because they don’t understand what it really means 🙂