Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a value type act like a reference type when it's property of a reference type?

Tags:

c#

.net

Why does 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;
    }
}

result in

bc2.Value == true

As bool is a value type I would have expected bc2.Value == false unless bc2.Value is boxed and stored on the heap.

I've found this method on Stack Overflow to tell if the value is boxed

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

But it says it's not boxed. I'm somewhat confused now, can anyone explain this to me?

like image 880
Gess Avatar asked Dec 14 '22 20:12

Gess


2 Answers

There is only one instance of BoolClass in your Main - the one created with

BoolClass bc1 = new BoolClass { Value = false }

The second variable bc2 refers to the same exact instance of BoolClass, along with all properties attached to that instance. This is because reference types do not get copied.

OneInstance

Therefore, there is only one Value property, and it belongs to the BoolClass instance. Any manipulations with that property will be seen through both references to the instance.

like image 162
Sergey Kalinichenko Avatar answered Dec 16 '22 08:12

Sergey Kalinichenko


Because you're creating only one instance of BoolClass (the line with 'new' in it). When assigning bc2, you're assigning it the same object reference as bc1, so they now point to the same object.

So, when assigning bc1.Value, you're changing the boolean on the same object as bc2 and therefore, it also contains the same value.

like image 28
allpro1337 Avatar answered Dec 16 '22 09:12

allpro1337