If we put address(this).balance inside a function, like this:

function getBalance() public view returns(uint) {
    return address(this).balance;

It works perfectly as it should.

However, it doesn't work in a state variable:

 uint public balance = address(this).balance;

It always outputs 0. Why is that?

1 Answer 1

uint public balance = address(this).balance;

sets the balance state variable to the the address' balance at the time the contract is created, which is 0. It will not update its value unless some function call explicitly updates its value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.