简体   繁体   中英

What is the difference between explicit and implicit type casts?

你能解释一下explicitimplicit类型转换的区别吗?

This is a little tricky because the "cast" syntax in C# actually does a range of different things (cast, primitive convert, bespoke convert, etc)

In an implicit cast, there is an obvious reference-preserving conversion between the two:

List<int> l = new List<int>();
IList<int> il = l;

The compiler can prove that this is safe just from static analysis ( List<int> is always an IList<int> )

With an explicit cast, either you are telling the compiler that you know more than it does - "please believe me, but check anyway":

List<int> l = new List<int>();
IList<int> il = l;
List<int> l2 = (List<int>)il;

Although this cast is possible , the compiler won't accept that all IList<int> s are actually List<int> - so we must tell it to let it by.


In an implicit primitive conversion (providedby the language spec), it is generally assumed that there is a safe, non-risky, non-lossy (caveat: see Jon's comment) conversion:

int i = 1;
float f = i;

With an explicit primitive conversion, it is likely that the conversion could lose data, or is non-obvious:

float f = 1;
int i = (int)f;

With bespoke operators, all bets are off, and you'd have to look at the documentation. It could be a reference-cast, or it could be anything . It may follow similar rules to primitive conversions (example: decimal ), or it could do anything randomly:

XNamespace ns = "http://abc/def"; // implicit
XAttribute attrib = GetAttrib();
int i = (int)attrib; // explicit (extracts text from attrib value and
                     // parses to an int)

Both of these run custom code that is context-specific.

What's the difference between the President of the United States and the President of Canada?

Since there is no President of Canada, it's hard to answer the question. The right thing to do is to push back and ask for clarification of the question. By "the President of Canada", does the questioner mean the Queen (ceremonial head of state), the Governor General (who can veto bills) or the Prime Minister (who effectively acts as the executive), or something else? Hard to say without clarification.

And even with clarification, it's a vague question. What differences do you want to know about?

Since there is no such thing as an "implicit cast" in C# it is hard to answer your question. In C#, casting is an operator. So I'll push back on it.

Did you mean to ask "what's the difference between an explicit conversion and an implicit conversion?" Or did you mean to ask about the semantics of the cast operator? Or the difference between the cast operator and other type conversion operators? Or situations in which cast operators can be "implicitly" inserted into your code by the compiler? (For example, the foreach loop and the += operator can both implicitly insert an invisible cast.)

Can you clarify the question? What two things are you asking for comparison of, and what sorts of differences are you interested in?

You might consider reading the "Conversions" chapter of the C# specification. Odds are good that any question you have about conversions are answered there.

int i = 2;

float a = i;        // Implicit
float b = (float)i; // Explicit

Explicit Conversions

If a conversion cannot be made without a risk of losing information then it is an explicit conversion.

For example -

class ExplicitConversions
{
    static void Main()
    {
        int x;
        double y = 6358.057;
        // Cast double to int.
        x = (int)y;
        System.Console.WriteLine(x);
    } 
}

Implicit Conversions

If a conversion can be made without a risk of losing information then it is an implicit conversion. No special syntax is required because the conversion is type safe and no data is lost.

For example -

class ImplicitConversions
{
    static void Main()
    {
        int x = 6714;
        double y;
        // Cast int to double.
        y = x;
        System.Console.WriteLine(y);
    } 
}

我认为这篇文章解释得最好。

Explicit cast:

int x = 0;
float y = 3.8f;

x += (int) y; //Explicit cast.

This tells the compiler that the cast was intentional and that you know that the fractional part will go lost. The compiler won't complain.

Implicit cast:

int x = 0;
float y = 3.8f;

x += y; //Implicit cast

The compiler will complain because the fractional part will be lost when converting float to int.

A simple search will give lots of informations in the net.
difference between implicit and explicit type

Explicit from MSDN -

If a conversion operation can cause exceptions or lose information, you should mark it explicit. This prevents the compiler from silently invoking the conversion operation with possibly unforeseen consequences.

Implicit from MSDN -

if the conversion is guaranteed not to cause a loss of data

Type Casting: Conversion of one data type to another data type. and it can be done in two ways.

Implicit Type Casting , Explicit Type Casting

Implicit type casting is performed by the compiler on its own when it encounters a mixed data type expression in the program. it is also known as automatic conversion as it is done by the compiler without the programmer's assistance. implicit casting doesn't require a casting operator.

Example:-

int a=42;
float b=a;

here b will contain typecast value of a, because while assigning value to b compiler typecasts the value of an into float then assigns it to b.

Explicit type casting is performed by the programmer. In this typecasting programmer tells the compiler to typecast one data type to another data type using type casting operator. but there is some risk of information loss is there, so one needs to be careful while doing it

Example:-

float a=42.12;
int b=(int)a;

here we explicitly converted float value of a to int while assigning it to int b. (int) is the typecasting operator with the type in which you wants to convert.

From a general point of view; here is the diff between the two type of Casts :

Implicit type casting is performed by the compiler on its own when it encounters a mixed data type expression in the program. it is also known as automatic conversion as it is done by compiler without programmer's assistance. implicit casting doesn't require a casting operator.

Explicit type casting is performed by the programmer. In this type casting programmer tells compiler to type cast one data type to another data type using type casting operator. but there is some risk of information loss is there, so one needs to be careful while doing it.

you can refer to This article for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM