- Learn C# in 7 days
- Gaurav Aroraa
- 250字
- 2021-07-08 09:51:27
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:

- Expert C++
- Python編程自學(xué)手冊(cè)
- RTC程序設(shè)計(jì):實(shí)時(shí)音視頻權(quán)威指南
- 零基礎(chǔ)學(xué)MQL:基于EA的自動(dòng)化交易編程
- 零基礎(chǔ)學(xué)Python網(wǎng)絡(luò)爬蟲案例實(shí)戰(zhàn)全流程詳解(入門與提高篇)
- 用案例學(xué)Java Web整合開發(fā)
- Visual Studio Code 權(quán)威指南
- Android移動(dòng)應(yīng)用開發(fā)項(xiàng)目教程
- SAP Web Dynpro for ABAP開發(fā)技術(shù)詳解:基礎(chǔ)應(yīng)用
- 用Python動(dòng)手學(xué)統(tǒng)計(jì)學(xué)
- Building a Media Center with Raspberry Pi
- Go Systems Programming
- JavaScript Unit Testing
- 算法訓(xùn)練營(yíng):海量圖解+競(jìng)賽刷題(入門篇)
- C# 10核心技術(shù)指南