< Day Day Up > |
Techniquelong l = 0; int i = 0; l = i; If however you need to convert a data type from a larger to a smaller size , you need to explicitly convert the value using the System.Convert class or through a technique known as casting : long l = 0; int i = 0; i = Convert.ToInt32( l ); i = (int) l; For any objects you want to convert to a string, simply use the ToString method, which is defined for all .NET value types: int i = 0; string s = i.ToString(); Every value type defined in the .NET Framework contains a static method named Parse. It allows you to convert a string value to that value type. The string itself must be formatted correctly or a FormatException will occur "string sNum = "3.1415936535"; double dNum = Double.Parse( sNum ); CommentsData conversion is a process that tends to occur frequently. The most frequent case is when you need to call a function whose parameters are different types than what you have been using in your application. Regardless of how different those two types are, an implicit or an explicit conversion will take place. Implicit conversion occurs when the data type you want to convert to is a larger size than the data type you are converting from. For example, if a method needs a long data type (64 bits in C#) and your variable is an int , then the compiler will perform the necessary implicit conversion for you. In other words, you can simply pass the int variable into the method that is expecting a long parameter, and it will work without any conversion necessary on your part. The high 32 bits of the long will simply be all zeros. If you need to convert a larger value to a smaller value, you have to perform an explicit conversion. The easiest way to determine whether you need to do so, other than memorizing all the conversion rules, is receiving an error from the compiler indicating that it could not perform an implicit conversion. To explicitly convert one data type to another, you can use the System.Convert class. This class contains several methods and several overloads of those methods to effectively perform explicit conversions. For example, to convert a long variable to an int , use the System.Convert.ToInt32 method, passing the long variable as the parameter. Looking at this class, you'll see most of the data conversions you need. A shorthand way of performing an explicit conversion is through a technique known as casting . You perform casting by prefacing the variable you want to convert with the data type to convert to within parenthesis. To cast a long to an int , you use the following: long l; int i = (int) l; |
< Day Day Up > |