What is the difference between explicit and implicit type casts?

后端 未结 10 892
太阳男子
太阳男子 2020-12-04 18:15

Can you please explain the difference between explicit and implicit type casts?

10条回答
  •  情深已故
    2020-12-04 18:20

    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 l = new List();
    IList il = l;
    

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

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

    List l = new List();
    IList il = l;
    List l2 = (List)il;
    

    Although this cast is possible, the compiler won't accept that all ILists are actually List - 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.

提交回复
热议问题