Say I have the following contract:
contract A {
uint[1] public MyArray;
constructor() public {
MyArray[0] = 56;
}
}
And I want to know the size of MyArray by looking it up from another contract. Naively, I would have thought that this would work:
contract B {
function getsize() public view returns (uint) {
A contr = A(addressOfA);
uint size = contr.MyArray.length;
return size;
}
}
The error I get is:
TypeError: Member "length" not found or not visible after argument-dependent lookup in function (uint256) view external returns (uint256). uint size = contr.MyArray.length;
Does this mean that contr.MyArray
is not considered as an array? Is there a way to get the length like this? I would ideally want to avoid writing any getter in contract A
because I am trying to reduce the code size in contract A
.
Thank you
Best Answer
Solidity creates getter functions for public state variables automatically. For example, the following will work:
In the case of arrays however, you can only get a single element from the array, rather than the entire array. From the Solidity documentation:
Basically, while you can do the following:
You cannot use
a.foo()
to read the entire array, and you will have to use a getter function like this for example: