I am curious to know if all casts in C# result in boxing, and if not, are all casts a costly operation?
Example taken from Boxing and Unboxing (C# Programming Guide)
int i = 123;
// The following line boxes i.
object o = i;
This line obviously causes boxing (wrapping up the int type as an object).
This is an operation that is considered costly, since it creates garbage that will be collected.
What about casts from 2 different types of reference types? what is the cost of that? can it be properly measured? (compared to the previous example)
For example:
public class A
{
}
public class B : A
{
}
var obj = new B();
var obj2 = (A)obj; // is this an "expensive" operation? this is not boxing
No. Only boxing conversions result in boxing, hence the name “boxing conversions”. Boxing conversions are all built-in conversions from value types to reference types — either to a class that the value type inherits from, or to an interface that it implements. (Or to an interface compatible with an interface it implements, via a covariant or contravariant reference conversion.)
No. Identity conversions are zero cost because the compiler can elide them entirely.
Implicit reference conversions are zero cost. The compiler can elide them entirely. That is, converting from Giraffe to its base type Animal, or Giraffe to its implemented interface type IAmATallMammal, are free.
Explicit reference conversions involve a runtime check to verify that the reference does in fact refer to an object of the desired type.
Whether that runtime check is “costly” or not depends on your budget.
Sure. Decide what resource is relevant to you — time, say — and then carefully measure your consumption of time with a stopwatch.
A question you did not ask but probably should have:
User-defined conversions are nothing more than a syntactic sugar for a method call; that method can take arbitrarily long, like any method.
Dynamic conversions start the compiler again at runtime; the compiler may take arbitrarily long to perform a type analysis, depending on how hard an analysis problem you choose to throw at it.