Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Hi im just wondering what the best practice for casting is.
Example;
C#
int MyInt = (int)SomeVariable;
int MyInt = Convert.ToInt32(SomeVariable);


Thanks in advance
Posted
Updated 1-Dec-11 0:34am
v2

 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 1-Dec-11 14:50pm    
Not a bad reference, my 5. It does not cover some other aspects such as dynamic casts and more.
I added some advice in my solution, please see.
--SA
You have two different things.
C#
// 1. a cast
int MyInt = (int)SomeVariable;

SomeVariable needs to be a type that can directly cast to an integer, i.e. a numeric, character or byte which is or has an integral part. Casting from float or double means you lose the fractional part, but that is useful at times.
C#
// 2. converter
int MyInt = Convert.ToInt32(SomeVariable);

In this case you are taking a value which cannot be directly referenced as a number (e.g. a string such as "1378") and parsing it into its constituent parts and converting to the value it represents.
 
Share this answer
 
Comments
[no name] 1-Dec-11 8:29am    
precisely! my 5!
Richard MacCutchan 1-Dec-11 8:34am    
Thanks.
Sergey Alexandrovich Kryukov 1-Dec-11 14:47pm    
All correct, my 5.
I added some more advice, please see.
--SA
BillWoodruff 1-Dec-11 21:08pm    
+5 Excellent right-to-the-point answer ! I sometimes wonder if the .NET syntax would be clearer if we distinguished the use of the word 'casting' as verb (as in this example) from the use of 'casting' with reference types via the 'as' operator. However, that's easy for me to say :), and typing 'as' sure is more finger-conserving than typing something like: someDerivedInstance TransformTo someBaseClass; :)
You can also use Int32.TryParse which allows you to convert if it's possible, and return a bool indicating success/failure.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 1-Dec-11 14:46pm    
Much better than "Convert", a 5.
--SA
Best, absolutely the best practice is no casting at all! In many cases, it's possible to design code without type cases. Use generics, in particular.

However, in some cases, type casting is unavoidable. Sometimes even dynamic casting using "as" is needed, but this is often a sign of OOP abuse. You did not ask about it, but it's important to know:
http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=VS.100%29.aspx[^].

See also http://msdn.microsoft.com/en-us/library/scekt9xw.aspx[^].

As to "Convert", to me, this is often a sign of lack of understanding (even when it works correctly). A cast is not conversion, a conversion is not a cast. A "classic" cast like (int)… is better, but not always applicable. In your case, it is probably not. If the input is string, it's much better to use Parse or TryParse, as it reflects the essence of what's actually done.

The cast like (int)… is mostly uses to cast downcasting (http://en.wikipedia.org/wiki/Downcasting[^], note the danger of it) and casting to a narrower type like int to short, int to byte, etc. In all cases, casting can fail, should be used with care. More exactly, it should be uses mostly when you can know in advance that the case is successful.

—SA
 
Share this answer
 
v2
Comments
Addy Tas 1-Dec-11 18:57pm    
Rather complete, my 5
Sergey Alexandrovich Kryukov 1-Dec-11 19:00pm    
Thank you, Addy.
--SA
BillWoodruff 1-Dec-11 21:01pm    
+5 great answer, SAK. Minor comments: casting via 'as' is only for reference types: so would be irrelevant to the Op's scenario here that uses integers. And, the new 'dynamic' keyword in .NET (for turning-off compile-time type checking, late (run-time) binding, etc.), probably makes it good to be very precise in how we use the word 'dynamic' now.
Richard MacCutchan 2-Dec-11 4:32am    
+5, some very good comments and advice
Have a look at this question on MSDN

http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/1ca53a60-e094-4073-ab33-27cca0bdbad4/[^]

* (int) will only convert types that can be represented as an integer.

So, you can't always use the (int) syntax. Depending on what you are trying to cast, Convert.ToInt32 or Int32.TryParse might be the option you need.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 1-Dec-11 14:49pm    
The problem is that OP's sample is incomplete, so the solutions can be different. I did not like the article you referenced very much, but you are right; I voted 4.
I added some more complete advice, please see.
Convert.ToInt32 is better.
 
Share this answer
 
Comments
Philippe Mori 1-Dec-11 20:05pm    
Why. Give at least a reason.
[no name] 1-Dec-11 21:22pm    
yes right
Best Practice for casting is Convert.ToInt32 compare to (int)

Because if result value is null in case of (int) casting it will throw exception.

But in case of Convert.ToInt32 if resulting value is null, it gives result. doesn't throw exception.
 
Share this answer
 
v2
Comments
lukeer 1-Dec-11 9:47am    
But that is converting, just as the method name indicates.

Casting should be a lot faster than converting. At times, this might count.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900