question

SougataGhosh-7881 avatar image
0 Votes"
SougataGhosh-7881 asked PeterFleischer-3316 commented

Value type Data: Sizeproperty of the FORM class

Hi,

I have read that whenever we access a value type data, we get a copy. y question is regarding the Size property of the FORM class. So what I realized is that we cannot write the following:

 Dim f As New MyForm()
 f.size.height = 15   'Doesn't Work
 f.size.height = 25   'Doesn't work

And the reason why we cant write this is because when the compiler resolves f.size.height then, it first evaluates f.size which RETURNS a value type data (SIZE property is of structure type) and therefore actually returns a copy. Therefore we are actually setting the size of a copy of the form through the form which the compiler disallows.

But we are allowed to write Console.WriteLine(form1.Size.Height). This statement works fine....Does that mean the height that gets printed is that of a duplicate (but same sized form)?

Any help would be greatly appreciated.

Regards,
Sougata



dotnet-visual-basic
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

PeterFleischer-3316 avatar image
0 Votes"
PeterFleischer-3316 answered PeterFleischer-3316 commented

Hi,
The preceding example fails because it creates only a temporary allocation for the Size structure returned by the Size property. A structure is a value type, and the temporary structure is not retained after the statement runs. The problem is resolved by declaring and using a variable for Size, which creates a more permanent allocation for the Size structure.

 Dim f As New MyForm()
 f.Size = New Size(f.Size.Width, 15) 
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

My question is completely different.....

0 Votes 0 ·

Hi,
when you assign a ValueType variable, you always get a copy of the value. A method (also the getter of a property) supplies a copy that can only be used from the stack (return value) for assignments.

When you assign a ReferenceType variable, you always get a copy of the reference to the object. The copy of the reference points to the same object as the original variable.

Explore the following code:

91108-x.png


0 Votes 0 ·
x.png (68.0 KiB)

I agree to what you have written. But the question is we are allowed to write Console.WriteLine(form1.Size.Height). This statement works fine....Does that mean the height that gets printed is that of a duplicate (but same sized form)?

0 Votes 0 ·
Show more comments