4

Layers is a jagged array of Node, and each node as source[] and destination[] which represents array of Theta.

Question is, why when I change the code on the fourth line, the fifth line still prints '0' after I linked those objects?

theta t = new theta();
layers[1][i].source[j] = t;
layers[0][j].destination[i] = t;
layers[0][j].destination[i].weight = 5;
Console.WriteLine(layers[1][i].source[j].weight);

struct theta
{
    public double weight;
    public theta(double _weight) { weight = _weight; }
}

class node
{
    public theta[] source;
    public theta[] destination;
    public double activation;
    public double delta;

    public node() { }
    public node(double x) { activation = x; }
}

Sample on how the layers are filled:

node n = new node();
n.destination = new theta[numberOfNodesPerHiddenLayer+1];
n.source = new theta[numberOfNodesPerHiddenLayer+1];
layers[i][j] = n;
Auromius
  • 49
  • 8
  • You should clarify how the `layers` array is filled. – Niels Keurentjes May 12 '13 at 19:14
  • Please post the entire outer/nested loops (if applicable) code snippet because it's unclear where indices i and j came from. Rgds, – Alexander Bell May 12 '13 at 19:16
  • change structure to class and everything will work. With the present use there is no point in having structure there – ashcliffe May 12 '13 at 19:17
  • Layers are instantiated individually on each of its dimension. Here's a sample of code on how the layers (which is an array of node) is filled: `node n = new node();` `n.destination = new theta[numberOfNodesPerHiddenLayer+1];` `n.source = new theta[numberOfNodesPerHiddenLayer+1];` `layers[i][j] = n;` – Auromius May 12 '13 at 19:18

2 Answers2

4

This is because Theta is a STRUCT, not class. Structs are implicitly copied. When you are doing:

theta t = new theta();
layers[1][i].source[j] = t;
layers[0][j].destination[i] = t;

you end up with three copies of 't'. One original, one at index 1,i and one at index 0,j. Then, you assign 5 to only one of the copies. All others stay unmodified. This is how structs are different from class: they are assigned by value copying, not by-reference.

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
  • Thank you! Your solution works perfectly! I thought `struct` was just another class but with limitations such as no functions/procedures for simplification sake. I should go read books more! D: – Auromius May 12 '13 at 19:22
0

That is because struct is a value-type (as opposed to a reference type) and has value-type copy-semantics. See for example this post: What is the difference between a reference type and value type in c#? for more information.

If you change the type of theta to class it will likely work the way you expect.

Community
  • 1
  • 1
DeCaf
  • 6,026
  • 1
  • 29
  • 51