Reference equality of value types

后端 未结 4 1000
臣服心动
臣服心动 2020-12-30 21:06

I have made some ref keyword tests and there is one think I can\'t understand:

static void Test(ref int a, ref int b)
{
    Console.WriteLine(In         


        
4条回答
  •  [愿得一人]
    2020-12-30 21:42

    I know, that int is a value type but here it should pass references to the same object.

    Yes, the reference passed to the method are the same, but they are boxed (converted to object/reference type) in the ReferenceEquals method.

    That is why the result of your test returns false, since you are comparing references of two different objects, due to boxing.

    See: Object.ReferenceEquals Method

    When comparing value types. If objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method. This means that if both objA and objB represent the same instance of a value type, the ReferenceEquals method nevertheless returns false

提交回复
热议问题