Pergunta

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;
Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top