Question with Vb.Net - private fields

I am looking at a class that has a method that takes a parameter that is of the same type of the class that contains that method.

Public Class test
   private _avalue as integer
   Public Sub CopyFrom(ByVal from as test)
     _avalue = from._avalue
   End Sub
End Class

      

When used in code

a.CopyFrom(b)

      

It looks like instance "a" has visibility to private members passed in instance "b" and string

_avalue = from._avalue 

      

runs without error by copying the private field from one instance of the object to another.

Does anyone know if this is by design. I was under the impression that the private field is only accessible to the object instance.

+2


source to share


2 answers


Scope private

is associated with a type, not an instance. So yeah, it's by design.



A class test

has knowledge of private parts of itself, so it can use those parts in other instances of the same type as well.

+2


source


You are writing something similar to a copy constructor.

Since the copy method / function is written inside the same class, it will have access to the private variables of any instance of its class.



+2


source







All Articles