Casting (C # programming guide)
Visual Studio 2005{
Changeversionclick ()
} "> Other Versions
- Visual Studio 2010
- Visual Studio 2008
Converting between data types can be done explicitly using a cast, but in some cases, implicit conversions are allowed. For example:
VB
C #C ++ F # jscriptcopy
static void TestCasting(){ int i = 10; float f = 0; f = i; // An implicit conversion, no data will be lost. f = 0.5F; i = (int)f; // An explicit conversion. Information will be lost.}
A cast explicitly invokes the conversion operator from one type to another. the cast will fail if no such conversion operator is defined. you can write custom conversion operators to convert between user-defined types. for more information about defining a conversion operator, see explicit (C # reference) and implicit (C # reference ).
{
Ca_click ('f5241fcb-4792-4ca3-994c-9934cefbf8e9', 'expand', 'collapse ')
} "Href =" javascript: void (0) ">
Example
The following program casts a double to an int. The program will not compile without the cast.
VB
C #C ++ F # jscriptcopy
class Test{ static void Main() { double x = 1234.7; int a; a = (int)x; // cast double to int System.Console.WriteLine(a); }}
{
Ca_click ('8b750198-2730-490c-b335-b8fda1c4d336 ', 'expand', 'collapse ')
} "Href =" javascript: void (0) ">
Output
1234
{
Ca_click ('8e9dbb62-7df4-108b-9004-472c6bba1ba7', 'expand', 'collapse ')
} "Href =" javascript: void (0) ">
C # Language Specification
For more information, see the following sections in the C # Language Specification:
7.6.6 cast expressions
6.1 implicit Conversions
6.2 Explicit conversions
{
Ca_click ('d2bbdc5a-154f-46dc-8d91-6e3dc7ed64a0 ', 'expand', 'collapse ')
} "Href =" javascript: void (0) ">
See also
Reference
Data Types (C # programming guide)
() Operator (C # reference)
Explicit (C # reference)
Implicit (C # reference)
Concepts
C # programming guide
Conversion operators (C # programming guide)
Generalized type conversion
Explicit Conversion
Exported type conversion