Link to home
Start Free TrialLog in
Avatar of GouthamAnand
GouthamAnand

asked on

Difference between type cast and Convert.int32 ?

Can any one explain me the difference between the below 2 statements.

status = (int)InvoiceStatus.VALID;

status = Convert.ToInt32(InvoiceStatus.VALID);

Which is better and faster? And when should I use which?
Avatar of Leon Teale
Leon Teale
Flag of United Kingdom of Great Britain and Northern Ireland image

They pretty much do the same thing.  If you're just changing data from one form to another for use, such as changing a "45" from a varchar to an int, use CAST; Convert offers more options than cast which may lead to more processing time.  And by this, I of course mean MINIMAL, not noticeable processing time.  Convert allows you to add a format style to your convertion, if you want it to.  For example, if you're changing a date to a string, you can say which part of the date to return instead of returning the whole thing and making .NET format it.
Casting will throw an exception if it fails or the input is null. The Convert class will return 0 if the input is null.
difference will depend on the type of variable2.

For instance, if InvoiceStatus.VALID has a value which is a string reference to
"23" then Convert.ToInt32 will parse the int. However, you can't *cast*
from a string to an int.
ASKER CERTIFIED SOLUTION
Avatar of Anurag Thakur
Anurag Thakur
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of GouthamAnand
GouthamAnand

ASKER

Thank you.