What's the best casting method in C# (c-style Vs. 'as')

.NET programming topics
Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

What's the best casting method in C# (c-style Vs. 'as')

Post by Saman » 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.

Code: Select all

int myVal = 100;
object obj = myVal;
string str = (string) obj;
'as': This will convert successfully.

Code: Select all

int myVal = 100;
object obj = myVal;
string str = obj as string;
Conclusion:
  • 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.
User avatar
ecig12
Posts: 1
Joined: Wed Feb 27, 2013 2:43 pm

Re: What's the best casting method in C# (c-style Vs. 'as')

Post by ecig12 » Wed Feb 27, 2013 2:52 pm

C# best casting method is type casting.

Convert a float value in int. int value in long. but you can't convert the long into float or double.
Char value convert char.

float-int-long-double-char-string
Post Reply

Return to “.NET Programming”