C# Data Type Conversion: Implicit Conversion, Explicit Conversion, and Casting

2019年12月9日 146点热度 0人点赞 1条评论
内容目录

C# provides two types of type conversion: explicit conversion and implicit conversion.

Explicit conversion: This type of conversion may cause exceptions, precision loss, and other issues. It requires intervention for the conversion operation.

Implicit conversion: This type of conversion does not change the original data's precision, will not cause exceptions, and will not result in any issues. The system performs this automatically.

If operations are performed on different types of data (addition, subtraction, multiplication, division, assignment, etc.), a type conversion is required before continuing the operations. Thus, type conversion is necessary.

 

Implicit Conversion

Implicit conversion is straightforward; when two or more data types are involved in an operation, the system will automatically perform implicit conversion without any interference.

For example:

        int i = 66666;
        long b = i;    // Assigning value to b after converting to long type

Generally, when multiple value types are calculated, the system will automatically perform implicit conversion, and it always converts to a larger data type without any change in precision, numerical size, and so on.

Explicit Conversion

The issue arises when you need to convert a long type data to int, or switch between string and int, especially when the decimal number is too high; this is when you must use explicit conversion.

 

Before continuing with the following tutorial, it is worth mentioning that:

char is an integer!

Although char stores characters rather than numbers, it is indeed an integer. Looking back at the above image, this is evident.

In other words, char can participate in arithmetic operations, but not directly; rather, it uses the underlying value. In C#, char values are based on Unicode. Through Unicode, any character can be interpreted as a number.

 

1. Using the ([type]) conversion operator

This method is applicable for value type conversion (string is a reference type).

Add ( [type] ) before the variable requiring conversion.

Please observe the differences in the following two images:

In the code of the second image, the second line is int b = (int)i;  

To convert, use the format ([type]) before the variable requiring conversion, such as (int), (float), (long).

Note that,

this method can only convert value type data.

Do not convert larger range types to smaller or convert floating-point types to integer types, and cannot convert out of range to smaller.

 

For example, converting float to int will automatically lose precision:

Output will be: 666

 - - -

When assigning a number greater than the type range, it will result in an overflow.

 

char can directly use int or long.

            int a ='1' + '3';  // Small to large
            char b = (char)a;  // Large to small
            int c = 'a' + '5';  // char can directly convert to int

  


Note the difference in the examples above; converting int directly to char will cause an error.

 

2. [Type].Parse()

 The ([type]) method cannot be used to convert between value types and reference types (string type).

However, each data type provides a Parse() method that allows converting a string into the corresponding numeric type.

int.Parse()

float.Parse()

... ...

See the example:

        string str = "666";
        long i = int.Parse(str);
        Console.WriteLine($"{i},{i.GetType()}");
        Console.ReadKey();

(Image shown)

 

Note that,

Parse() is specifically designed for converting string types to value types!

Parse() is for converting strings that conform to numeric formats!

 

The following examples showcase incorrect usage!

 Parse() is meant to convert strings that conform to numeric formats, which means,

  • The content within the ( ) must be a string!
  • The content of the string must be numeric!

Example 1: The content within the ( ) is not a string

Example 2: The content of the variable str is not in valid numeric format

 

3. [Type].TryParse()

Format is as follows:

int.TryParse()

float.TryParse()

... ...

.TryParse()  is similar to .Parse()  but the usage format is slightly different.

[type].TryParse(string to change, out variable to store the result);

The key difference is that  .TryParse()  doesn't throw an exception on conversion failure; instead, it returns false.

Example:

        string str = "666";
        int i;
        bool b = int.TryParse(str,out i);    // Receiving conversion result
Or
    string str = "666";
    int i;
    int.TryParse(str,out i);    // Not receiving conversion result

If you are unsure about using out, please refer to out parameters/ref parameters/params variable parameters in C#

4. System.Convert

Method examples:

System.Convert.ToSingle();
System.Convert.ToInt32();
System.Convert.ToDouble();

... ...

System.Convert  allows conversion from one type to another.

Common type list: char, sbyte, short, int, long, uint, ulong, float, double, decimal, string, bool ... ...

However, format support is also required!

        string str = "666";
        int a= System.Convert.ToInt32(str);        // Correct
    string str = "666.66";
    int a= System.Convert.ToInt32(str);        // Error

    int a = 66666;
    bool c = System.Convert.ToBoolean(a);        // Correct

    string str = "666.66";
    bool c = System.Convert.ToBoolean(str);        // Error

  System.Convert also requires attention to format in order to convert successfully.

       Similarly, this method may also result in precision and numerical size changes.

 

 5. System.Convert

.ToString()

Each data type provides a method to convert to string type: ToString()

Whether it is a value type or various reference types like DateTime.

The usage of ToString() is quite simple, please pay attention to the red background part of the following examples

using System;
using System.IO;

public class Test {

</span><span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> Main()
{
    </span><span style="color: #0000ff;">int</span> a = <span style="color: #800080;">666</span><span style="color: #000000;">;
    </span><span style="color: #0000ff;">string</span> aa =<span style="color: #000000;"><span style="background-color: #ff0000;"> a.ToString()</span>;
    Console.WriteLine($</span><span style="color: #800000;">"</span><span style="color: #800000;">{aa}</span><span style="color: #800000;">"</span><span style="color: #000000;">);

    </span><span style="color: #0000ff;">float</span> b = <span style="color: #800080;">666.666F</span><span style="color: #000000;">;
    </span><span style="color: #0000ff;">string</span> bb =<span style="color: #000000;"><span style="background-color: #ff0000;"> b.ToString()</span>;
    Console.WriteLine($</span><span style="color: #800000;">"</span><span style="color: #800000;">{bb}</span><span style="color: #800000;">"</span><span style="color: #000000;">);

    DateTime c </span>=<span style="color: #000000;"> DateTime.Now;
    </span><span style="color: #0000ff;">string</span> cc =<span style="color: #000000;"><span style="background-color: #ff0000;"> c.ToString()</span>;
    Console.WriteLine($</span><span style="color: #800000;">"</span><span style="color: #800000;">{cc}</span><span style="color: #800000;">"</span><span style="color: #000000;">);

    FileInfo d </span>= <span style="color: #0000ff;">new</span> FileInfo(<span style="color: #800000;">"</span><span style="color: #800000;">E:\\test.txt</span><span style="color: #800000;">"</span><span style="color: #000000;">);
    </span><span style="color: #0000ff;">string</span> dd =<span style="color: #000000;"><span style="background-color: #ff0000;"> d.ToString()</span>;
    Console.WriteLine($</span><span style="color: #800000;">"</span><span style="color: #800000;">{dd}</span><span style="color: #800000;">"</span><span style="color: #000000;">);

    </span><span style="color: #0000ff;">string</span><span style="color: #000000;"> ee;
    </span><span style="color: #0000ff;">try</span><span style="color: #000000;">
    {
        </span><span style="color: #0000ff;">int</span> x = <span style="color: #800080;">1</span><span style="color: #000000;">;
        </span><span style="color: #0000ff;">int</span> y = <span style="color: #800080;">0</span><span style="color: #000000;">;
        </span><span style="color: #0000ff;">int</span> e = x /<span style="color: #000000;"> y;
    }
    </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
    {
        ee </span>=<span style="color: #000000;"> ex.<span style="background-color: #ff0000;">ToString()</span>;
        Console.WriteLine($</span><span style="color: #800000;">"</span><span style="color: #800000;">{ee}</span><span style="color: #800000;">"</span><span style="color: #000000;">);
    }


    Console.ReadKey();
}

}

Did you see that? No matter the type, just append ToString() and you can output the string type content. (Not converting to string type!)

Of course, ToString() is a method and provides several overloaded TOString() methods for each type, such as that of DateTime's

public string ToString(string format, IFormatProvider provider);
public string ToString(string format);
public string ToString(IFormatProvider provider);
public override string ToString();

 

No need to elaborate on other aspects.

 

Copy the following code into the console and see what the output is

using System;
using System.IO;

public class Test {

</span><span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> Main()
{
    </span><span style="color: #0000ff;">int</span> a = <span style="color: #800080;">666</span><span style="color: #000000;">;
    </span><span style="color: #0000ff;">string</span> aa =<span style="color: #000000;"> a.ToString();
    Console.WriteLine($</span><span style="color: #800000;">"</span><span style="color: #800000;">{aa}</span><span style="color: #800000;">"</span><span style="color: #000000;">);

    </span><span style="color: #0000ff;">float</span> b = <span style="color: #800080;">666.666F</span><span style="color: #000000;">;
    </span><span style="color: #0000ff;">string</span> bb =<span style="color: #000000;"> b.ToString();
    Console.WriteLine($</span><span style="color: #800000;">"</span><span style="color: #800000;">{bb}</span><span style="color: #800000;">"</span><span style="color: #000000;">);

    DateTime c </span>=<span style="color: #000000;"> DateTime.Now;
    </span><span style="color: #0000ff;">string</span> cc =<span style="color: #000000;"> c.ToString();
    Console.WriteLine($</span><span style="color: #800000;">"</span><span style="color: #800000;">{cc}</span><span style="color: #800000;">"</span><span style="color: #000000;">);

    FileInfo d </span>= <span style="color: #0000ff;">new</span> FileInfo(<span style="color: #800000;">"</span><span style="color: #800000;">E:\\test.txt</span><span style="color: #800000;">"</span><span style="color: #000000;">);
    </span><span style="color: #0000ff;">string</span> dd =<span style="color: #000000;"> d.ToString();
    Console.WriteLine($</span><span style="color: #800000;">"</span><span style="color: #800000;">{dd}</span><span style="color: #800000;">"</span><span style="color: #000000;">);

    </span><span style="color: #0000ff;">string</span><span style="color: #000000;"> ee;
    </span><span style="color: #0000ff;">try</span><span style="color: #000000;">
    {
        </span><span style="color: #0000ff;">int</span> x = <span style="color: #800080;">1</span><span style="color: #000000;">;
        </span><span style="color: #0000ff;">int</span> y = <span style="color: #800080;">0</span><span style="color: #000000;">;
        </span><span style="color: #0000ff;">int</span> e = x /<span style="color: #000000;"> y;
    }
    </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex)
    {
        ee </span>=<span style="color: #000000;"> ex.ToString();
        Console.WriteLine($</span><span style="color: #800000;">"</span><span style="color: #800000;">{ee}</span><span style="color: #800000;">"</span><span style="color: #000000;">);
    }


    Console.ReadKey();
}

}

 

痴者工良

高级程序员劝退师

文章评论