Familiarize yourself with C#data types.
There are two basic types in C#, value type and reference type. Value types can also be subdivided into built-in value types, structures, and enumerations. Reference types can be subdivided into class types, interfaces, delegates, and so on.
- Value type
Built-in value types are integer, floating-point, bool, and so on, while structure is a special value type, which is an abstract type, System.ValueType's directly derived class, while System.ValueType itself is directly from System.Object derives, so the struct has all the privileges and restrictions of the value type. - reference type
Reference type variables, also known as objects, store references to actual data. Built-in reference types are object type, dynamic type, and string type. - boxing and unboxing
Boxing and unboxing are operations to be performed when value types and reference types convert to each other.
(1) Boxing occurs when a value type is converted to a reference type.
(2) Unboxing occurs when a reference type is converted to a value type.
using System; namespace Project1 { class Program { static void Main(string[] args) { Console.WriteLine("Size of byte: {0}", sizeof(byte)); Console.WriteLine("Size of char: {0}", sizeof(char)); Console.WriteLine("Size of short: {0}", sizeof(short)); Console.WriteLine("Size of int: {0}", sizeof(int)); Console.WriteLine("Size of double: {0}", sizeof(double)); Console.ReadKey(); } } }
[Procedural Analysis] This example calculates the size of byte, char, short, int, and double types in memory by using the sizeof method. Since the result calculated by the sizeof method is in bytes, byte is 8 bits, which happens to be 1 byte, so the output is 1; Char is 16 bits, exactly 2 bytes; Both int and short are 32 bits, which is exactly 4 bytes; The final double is 64 bits, which is exactly 8 bytes. Therefore, the storage space of these five value types is 1, 2, 4, 4, 8.
Size of byte: 1 Size of char: 2 Size of short: 2 Size of int: 4 Size of double: 8
using System; namespace Project3 { class Program { static void Main(string[] args) { dynamic dyn = 1; object obj = 1; // Compile-time type Console.WriteLine(dyn.GetType()); Console.WriteLine(obj.GetType()); Console.ReadKey(); } } }
This example demonstrates the use of dynamic. The code first defines the dyn and obj variables of type dynamic and assigns them a value of 1. The GetType() method is then used to output the data type of the two variables at compile time.
System.Int32 System.Int32
Master C#data type conversion.
Type conversion is fundamentally type casting, or the conversion of data from one type to another. In C#, transformations are classified as implicit and explicit.
Implicit Conversion
Implicit type conversion refers to the C#default secure conversion that does not result in data loss. Implicit transformations can occur in many situations, including method calls and assignment statements.
The following points should be noted about implicit type conversion.
(1) Accuracy may be lost when converting from int, uint, long or ulong to float, and from long or ulong to double.
(2) There is no implicit conversion for char type.
(3) There is no implicit conversion between floating point type and decimal type.
(4) Constant expressions of type int can be converted to sbyte, byte, short, ushort, uint or ulong if the value of the constant expression is within the range of the target type.
Explicit Conversion
When a type conversion may result in data loss, the compiler will require an explicit conversion. An explicit conversion is also known as a cast. Coercion is a way to explicitly inform the compiler user that a conversion is intended and that the user knows that data loss may occur. If you want to perform a cast, you need to specify the type to cast to in parentheses before the value or variable you want to convert.
using System; namespace Project4 { class Program { static void Main(string[] args) { double d = 314.159; int i; // Cast double to int i = (int)d; Console.WriteLine(i); Console.ReadKey(); } } }
Explicit conversion can result in reduced precision or exception throwing, so the following points need to be noted.
(1) When converting a decimal value to an integer type, it rounds to zero the nearest integer value. If the resulting integer value is outside the range of the target type, an overflow error will result.
(2) When a double or float value is converted to an integer type, the value is truncated. If the resulting integer value is outside the target range, the result will depend on the overflow check context. In the context checked, an overflow error is raised; In an unchecked context, the result is an unspecified value for the target type. (3) When double is converted to float, the double value is rounded to the closest float value. If the double value is too small or too large to match the target type, the result will be zero or infinity.
(4) When a float or double is converted to a decimal, the source value is converted to a decimal representation and rounded to the nearest number after the 28th decimal. Depending on the value of the source value, one of the following results may occur:
1 If the source value is too small to be expressed as a decimal, the result is zero.
(2) If the source value is NaN (non-numeric), infinite, or too large to be represented as a decimal, an overflow error is raised.
(5) When decimal is converted to float or double, the decimal value is rounded to the nearest double or float value.
Convert for any type conversion
If the type is compatible with two variables, you can use implicit or cast, but if the two variables are incompatible, such as string and int or string and double, the user needs a conversion factory called Convert to convert.
using System; namespace Project5 { class Program { static void Main(string[] args) { string str = "123456"; //Variable str defining string type int a = Convert.ToInt32(str); //Convert class method converts string to int type Console.WriteLine(a); double d = Convert.ToDouble(str); //Convert class method converts string to double type Console.WriteLine(d); Console.ReadKey(); } } }
This example demonstrates the conversion method of Convert class. In the code, a variable str of string type is defined and assigned a value of "123456"; The data from str is then converted to int and double types, respectively, by the ToInt32 method.
123456 123456
Conversion between values and strings
In C#there is not only a conversion between numeric data types, but also between strings and numbers, but in different ways.
- Convert numeric to character
Converting numeric data to strings is accomplished using the ToString() method. - Convert String to Numeric
Converting string data to a numeric type uses the Pares() method.
(1) Convert the string type to an integer using the int.Pares() method.
(2) Use double.Pares() method that converts a string type to a double-precision floating-point type.
(3) Use float.Pares() method that converts a string type to a single-precision floating-point type.
Convert. Differences between ToInt32(), (int) and int.Parse()
There are many ways to convert data in C#This section focuses on Convert. Differences between ToInt32(), (int) and int.Parse(). During the actual development of a project, the types that need to be converted are roughly divided into the following three categories:
(1) Type conversion of null values.
For null values, (int) cast and int.Parse() cannot accept null from the point of view of run error; Convert.ToInt32() actually makes a judgment before the conversion, and if the parameter is null, it returns 0 directly.
(2) Converting number types, mainly testing double and long types.
For floating-point trade-offs, only Convert is a floating-point type. ToInt32() and (int) can be converted, but they are also trade-offs. Convert.ToInt32() takes the trade-off of rounding, while (int) intercepts the floating-point integer part and ignores the decimal part.
(3) Convert string type.
Convert.ToInt32() can be converted to many types (such as bool, DateTime, and so on), and int.Parse() can only be an integer string type (i.e., after various integer ToString(), and cannot be a floating point type, otherwise int.Parse() will have an incorrect string format for input), (int) can only be a numeric type (such as float, int, uint, and so on).
using System; namespace Project6 { class Program { static void Main(string[] args) { int a = 75; float b = 53.005f; double c = 2345.7652; string str1, str2, str3; Console.WriteLine("Convert numeric to character:"); str1 = a.ToString(); str2 = b.ToString(); str3 = c.ToString(); Console.WriteLine("str1={0}\nstr2={1}\nstr3={2}", str1, str2, str3); Console.WriteLine("Convert string to numeric type:"); int x = int.Parse(str1); float y = float.Parse(str2); double z = double.Parse(str3); Console.WriteLine("x={0}\ny={1}\nz={2}", x, y, z); Console.ReadKey(); } } }
This example demonstrates the conversion between a numeric value and a string. In the code, three variables a, b, c are defined and initialized. Next, the ToString method is called to convert the three variables into strings. Finally, the Parse method is called to convert the converted String to numeric data.
Convert numeric to character: str1=75 str2=53.005 str3=2345.7652 Convert string to numeric type: x=75 y=53.005 z=2345.7652