C# tutorial [3] data type conversion

Keywords: C#

This article was first published in Personal blog , it's better to watch personal blog

C # is a strongly typed language with strict requirements for types. There are two ways of type conversion: implicit type conversion and explicit type conversion.

Implicit type conversion

int a = 5;
double b = 1.5;
double c = a + b;
System.Console.WriteLine(c);

Like this, there is no special processing on the source code, but the compiler automatically makes an implicit conversion from int type to double type.

However, implicit type conversion is not allowed between many types. See the following example.

double a = 1.5;
int b = a;
System.Console.WriteLine(b);

When compiling on the author's computer, there will be such an error:

error CS0266 Cannot implicitly convert type 'double' to 'int'

Therefore, we need to correct it with explicit type conversion.

Explicit type conversion

The second line of the above example should read as follows:

int b = (int)a;

Syntax is to add a set of parentheses before the variable to be converted and write the type name to be converted. All implicit type conversions can be written explicitly.

But the result of writing the output in this way is 1, not the imaginary rounding 2.

Using explicit type conversion will lose the precision of data, which is why the compiler does not automatically perform explicit type conversion. Explicit type conversion is also called forced type conversion.

Moreover, explicit type conversion can not be carried out between all types. For example, the following is also wrong:

double a = (double)"5.5";

Note: in many other programming languages, int can be implicitly converted to bool, but errors will be reported in C # either implicitly or explicitly. Convert.ToBoolean() mentioned later should be used

In order to solve the above problems, we will introduce the use of methods for type conversion.

Type conversion using method

Use the ToString() method

ToString() method can be used for all types, as follows:

int a = 5;
string b = a.ToString();

Use the Convert.ToInt32() method

Convert is the class name and ToInt32() is the method name. The convert class provides many conversion methods, such as: ToChar(), ToDouble(), ToBoolean()

For example:

int a = Convert.ToInt32("5.0");

Use the int.Parse() method

The Parse() method is used to convert a string to another type

Note: parameters of Parse() method can only be strings

Use the type name. Parse (variable to be converted); that will do

For example:

string a = "5";
int b = int.Parse(a);

Although the int type is used in the example, virtually all numeric types have similar methods.

However, when converting the string "apple" to int, an error will still be reported, resulting in the program can not continue to run, and we don't really want him to convert apple to int. at this time, we can use the TryParse() method.

Use methods such as int.TryParse()

The instructions in Microsoft's official tutorial are as follows:

The TryParse() method can perform multiple operations at the same time:

  1. It attempts to parse the string into a given numeric data type.

  2. If successful, it stores the converted value in the out parameter.

  3. It returns a Boolean value indicating whether the operation was successful.

A similar TryParse() method can be used for all numeric data types.

For example:

double result;
string str = "5.5";
bool a = double.TryParse(str, out result); // result is the "out parameter" in Article 2 of the description 
System.Console.WriteLine($"a = {a}\nresult = {result}\n");

At this time, the output result should be:

a = True
result = 5.5

Example: (from Microsoft official documents) link)

Meaning:

A string array values is known

string[] values = { "12.3", "45", "ABC", "11", "DEF" };

Loop through each value in the string array. For each value, the following rules are met:

Rule 1: if the value is a letter, connect it to form a message

Rule 2: if the value is a number, add it to the total value

Sample output:

Message: ABCDEF
Total: 68.3

Example code:

official:

using System;

string[] values = { "12.3", "45", "ABC", "11", "DEF" };

decimal total = 0m;
string message = "";

foreach (var value in values)
{
    decimal number;
    if (decimal.TryParse(value, out number))
    {
        total += number;
    } else
    {
        message += value;
    }
}

Console.WriteLine($"Message: {message}");
Console.WriteLine($"Total: {total}");

Author's version:

using System;

string[] values = { "12.3", "45", "ABC", "11", "DEF" };

decimal total = 0.0m;
string message = "";

foreach (string v in values)
{
    if (decimal.TryParse(v, out decimal curr)) total += curr; // Writing the curr variable in this way will only take effect within the scope of the if statement
    else message += v; 
}

Console.WriteLine($"Messagae: {message}\nTotal: {total}\n");

Other precautions:

When trying to convert the string "5.5" to type int, the following two methods are wrong:

int a = Convert.ToInt32("5.5");
int a = int.Parse("5.5");

The correct way is to convert the string "5.5" to double and then to int, such as the following two methods:

int a = (int)Convert.ToDouble("5.5");
int a = (int)Double.Parse("5.5");

Posted by dream25 on Sun, 28 Nov 2021 00:37:32 -0800