What's the best casting method in C# (c-style Vs. 'as')
Posted: Fri Jul 22, 2011 3:29 pm
The most obvious difference is that a C style case will throw and exception if the cast fails and the "as" style cast will simply return null. So first you need to take into consideration what these differences will have on your code. Will you need to wrap every cast in try/catch blocks? Not if you use the "as" style, but you will need to check for null.
c-style casting: This will throw InvalidCastException.
'as': This will convert successfully.
Conclusion:
c-style casting: This will throw InvalidCastException.
Code: Select all
int myVal = 100;
object obj = myVal;
string str = (string) obj;
Code: Select all
int myVal = 100;
object obj = myVal;
string str = obj as string;
- If you are sure that source is also from same datatype like destination then you can use general casting(UnBoxing) which gives better performance since it is costly to send an exception.
- If you are NOT sure that whether source will have same datatype like destination or not, then you can use c-style casting which gives more flexibility.