官术网_书友最值得收藏!

Explicit conversion

Explicit conversion is the conversion that is performed by the user explicitly with the use of the cast operator; that's why this is also known as type casting. Explicit conversion is also possible using built-in type conversion methods. For more information, refer to https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/explicit-numeric-conversions-table.

Let's take a look at the following code snippet, which shows implicit/explicit type conversion in action:

private static void ImplicitExplicitTypeConversionExample() 
{ 
WriteLine("Implicit conversion"); 
int numberInt = 2589; 
double doubleNumber = numberInt; // implicit type conversion 

WriteLine($"{nameof(numberInt)} of type:{numberInt.GetType().FullName} has value:{numberInt}"); 
WriteLine($"{nameof(doubleNumber)} of type:{doubleNumber.GetType().FullName} implicitly type casted and has value:{doubleNumber}"); 
 
WriteLine("Implicit conversion"); 
doubleNumber = 2589.05D; 
numberInt = (int)doubleNumber; //explicit type conversion 
WriteLine($"{nameof(doubleNumber)} of type:{doubleNumber.GetType().FullName} has value:{doubleNumber}"); 
WriteLine($"{nameof(numberInt)} of type:{numberInt.GetType().FullName} explicitly type casted and has value:{numberInt}"); 
} 

In the preceding code-snippet, we discussed implicit and explicit conversion when we assign a variable numberInt of int type to a variable doubleNumber of double type, which is called implicit type conversion, and the reverse is an explicit type conversion that requires a casting using int. Note that implicitly, type conversion does not require any casting, but explicitly, conversion requires type casting, and there are chances for loss of data during explicit conversion. For instance, our explicit conversion from double to int would result in a loss of data (all precision would be truncated while a value is assigned to int type variable). This code produces the following result:

The two most important language fundamentals are type conversion and casting. To know more about these two, refer to https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions.
主站蜘蛛池模板: 昔阳县| 柘城县| 固始县| 东乡县| 枝江市| 鹰潭市| 静乐县| 朝阳县| 彰化县| 庆阳市| 巴里| 开阳县| 和静县| 龙南县| 巴里| 夏邑县| 德保县| 新源县| 门头沟区| 湘阴县| 奉新县| 潢川县| 荥阳市| 延津县| 两当县| 霍林郭勒市| 红安县| 都安| 仲巴县| 定结县| 曲沃县| 冷水江市| 武隆县| 治县。| 抚顺县| 玉树县| 邻水| 象山县| 绵阳市| 广宗县| 鸡西市|