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)
I am curious to know if all casts in C# result in boxing,
No. Boxing is a very special operation that means treating an instance of a value type as an instance of a reference type. For reference type conversion to reference type conversion, the concept plays no role.
are all casts a costly operation?
Short answer: No.
Long answer: Define costly. Still no, though.
What about casts from 2 different types of reference types? what is the cost of that?
Well, what if it's just a derived to base reference conversion? That's BLAZINGLY fast because nothing happens.
Other, user-defined conversions, could be "slow", they could be "fast."
This one is "slow."
class A { public int Foo { get; set; } }
class B {
public int Foo { get; set; }
static Random rg = new Random();
static explicit operator A(B b) {
Thread.Sleep(rg.Next());
return new A { Foo = b.Foo; }
}
}
This one is "fast."
class A { public int Foo { get; set; } }
class B {
public int Foo { get; set; }
static Random rg = new Random();
static explicit operator A(B b) {
return new A { Foo = b.Foo; }
}
}
var obj2 = (A)obj;
// is this an "expensive" operation? this is not boxing
No, it's "cheap."