question about passing by reference...
I have this code:
Code:
private void button1_Click(object sender, System.EventArgs e)
{
class[] b;
b = new class[1];
func(b);
}
private void func(class[] a)
{
func2(a[0]);
}
private void func2(class a)
{
a = new class();
a.member1 = "hello";
}
after the code goes through func2(), a[0] is still "undefined". Shouldn't a[0] be an instance with property member1 equaling to "hello"? I'm confused here.
I "could" put "ref" in the declaration, but I've always thought that in .net, classes are always passed by reference.
Re: question about passing by reference...
Classes are NOT always passed by reference. How you pass a parameter to a method refers to the VARIABLE, and we all know that value type variables contain an object while reference type variables do not, so it stands to reason that value types and reference types would behave differently.
If you pass a value type variable by value then you are passing a copy of an object, so any changes you make will not be reflected in the original . If you pass a value type varibale by reference then you're essentially passing the object itself, so any changes you make will be reflected in the original.
If you pass a reference type variable by value then you are passing a copy of a reference, i.e. another variable that refers to the same object, so any changes you make to the object will be reflected in the original, but if you assign a new object to the variable then that will not be reflected in the original. If you pass a reference type variable by reference then you are essentially passing the original reference, so any changes you make to the object or the variable will be reflected in the original.
In summary:
value type by value: no changes will stick
value type by reference: all changes will stick
reference type by value: changes to properties will stick but assigning a new object will not
reference type by reference: all changes will stick
For the purposes of the above, an element of an array is considered to be a property of a reference type object.
Re: question about passing by reference...
I finally got it. The "new" instance was being created inside the function(func2), so when it leaves the function or the "scope", the data is basically garbage collected. Thanks for the response.