Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a value type property in a reference type contain boxed value?

Tags:

c#

Lets say we have a type:

public class SomeClass
{
    public int intProperty { get; set; }
    ...
}

What will happen when I pass the property in a method like this?

var obj = new SomeClass();
obj.intProperty = 1;

SomeMethod(obj.intProperty);

public void SomeMethod(int value) { ... }

Will the passing of intProperty copy the value from the property like value types usually do?

like image 235
Aleksandr Sheianov Avatar asked Feb 26 '26 13:02

Aleksandr Sheianov


1 Answers

Does a value type property in a reference type contain boxed value?

No, it contains the value (int) itself (at least in current C# implementations I know of). If you want to dive deeper into the CLR implementation details check out Managed object internals article series:

The layout of a managed object is pretty simple: a managed object contains instance data, a pointer to a meta-data (a.k.a. method table pointer) and a bag of internal information also known as an object header.

enter image description here

What will happen when I pass the property in a method like this?

The value of SomeClass.intProperty (via getter call) will be copied and passed as parameter to SomeMethod call.

Will the passing of intProperty copy the value from the property like value types usually do?

Yes. If your concern is that the SomeMethod can somehow change the value of the SomeClass.intProperty - then no, it can't (though it has nothing to do with boxing/unboxing):

SomeMethod(obj.intProperty);
Console.WriteLine(obj.intProperty);// Prints "1"

void SomeMethod(int value) 
{  
    value = 42;
    Console.WriteLine(value); // Prints "42"
}

P.S.

I highly recommend to follow standard naming conventions, i.e. Pascal case for properties here - SomeClass.intProperty -> SomeClass.IntProperty

like image 109
Guru Stron Avatar answered Mar 01 '26 02:03

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!