Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The simple answer is: it depends.</p> <p>For value types, casting will involve genuinely converting it to a different type. For instance:</p> <pre><code>float f = 1.5f; int i = (int) f; // Conversion </code></pre> <p>When the casting expression unboxes, the result (assuming it works) is <em>usually</em> just a copy of what was in the box, with the same type. There are exceptions, however - you can unbox from a boxed int to an enum (with an underlying type of int) and vice versa; likewise you can unbox from a boxed int to a Nullable&lt;int&gt;.</p> <p>When the casting expression is from one reference type to another and no user-defined conversion is involved, there's no conversion as far as the object itself is concerned - only the type of the <em>reference</em> "changes" - and that's really only the way that the value is regarded, rather than the reference itself (which will be the same bits as before). For example:</p> <pre><code>object o = "hello"; string x = (string) o; // No data is "converted"; x and o refer to the same object </code></pre> <p>When user-defined conversions get involved, this <em>usually</em> entails returning a different object/value. For example, you could define a conversion to string for your own type - and this would certainly not be the same data as your own object. (It might be an existing string referred to from your object already, of course.) In my experience user-defined conversions usually exist between value types rather than reference types, so this is rarely an issue.</p> <p>All of these count as conversions in terms of the specification - but they don't all count as converting an <em>object</em> into an <em>object</em> of a different type. I suspect this is a case of Jesse Liberty being loose with terminology - I've noticed that in Programming C# 3.0, which I've just been reading.</p> <p>Does that cover everything?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload