Why does a value type act as a reference type when this property is a reference type?

Why is this:

public class BoolClass
{
    public bool Value { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        BoolClass bc1 = new BoolClass { Value = false };
        BoolClass bc2 = bc1;
        bc1.Value = true;
    }
}

will result in

bc2.Value == true

As boolis the type of value I would expect bc2.Value == falseif it bc2.Valuedoes not fit in the cell and is not stored on the heap.

I found this method in Stack Overflow to find out if a value is included

public static bool IsBoxed<T>(T value)
{
    return 
        (typeof(T).IsInterface || typeof(T) == typeof(object)) &&
        value != null &&
        value.GetType().IsValueType;
}

But he says it's not in the box. I'm a little confused, can someone explain this to me?

+4
source share
4 answers

There Mainis only one instance in yours BoolClass- one that is created using

BoolClass bc1 = new BoolClass { Value = false }

The second variable bc2refers to the same instance BoolClass, as well as to all properties attached to this instance. This is because link types are not copied.

Oneinstance

, Value, BoolClass. .

+8

BoolClass ( "" ). bc2 , bc1, .

, bc1.Value , bc2, .

+4

, , - . , new, .Ex -

  BoolClass bc1 = new BoolClass { Value = false };
  BoolClass bc2 = new BoolClass();
  bc2.Value = bc1.Value
  bc1.Value = true;

bc2.Value false

0

BooClass:

BoolClass bc1 = new BoolClass { Value = false };

And then apply the object reference to another bc2 object reference:

BoolClass bc2 = bc1;

Therefore, bc2 and bc1 point to the same instance of BooClass.

0
source

Source: https://habr.com/ru/post/1686642/


All Articles