Do interface variables have value-type or reference-type semantics?

后端 未结 4 628
醉酒成梦
醉酒成梦 2021-02-02 17:13

Do interface variables have value-type or reference-type semantics?

Interfaces are implemented by types, and those types are either value types or reference types. Obvi

4条回答
  •  别那么骄傲
    2021-02-02 17:23

    A variable or field whose type is IComparable is a reference-type variable or field, regardless of the type of the value assigned to that field. This means that x in the sample code is boxed.

    A simple test will demonstrate that. The test is based on the fact that you can only unbox a value type to its original type (and the nullable version of that type):

        [TestMethod, ExpectedException(typeof(InvalidCastException))]
        public void BoxingTest()
        {
            IComparable i = 42;
            byte b = (byte)i;      //exception: not allowed to unbox an int to any type other than int
            Assert.AreEqual(42, b);
            Assert.Fail();
        }
    

    EDIT

    On top of that, the C# specification specifically defines reference-type as comprising class types, interface types, array types and delegate types.

    EDIT 2

    As Marc Gravell points out in his answer, a generic type with an interface constraint is a different case. This doesn't cause boxing.

提交回复
热议问题