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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With