Do all C# casts result in boxing/unboxing

后端 未结 3 1670
南方客
南方客 2021-02-07 19:00

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)

3条回答
  •  隐瞒了意图╮
    2021-02-07 19:47

    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."

提交回复
热议问题