2

I have been learning and working on Solidity for quite a while now. One thing that I have seen in many codes but did not understand was typecasting (looks like typecasting to me) of addresses to a contract type. When and why is this required ? A few example use cases with explanation would be really helpful. This is one of the codes that I found -

contract MyContract {
}

contract NewContract {
    MyContract a;

    function setMyContractAddress(address _contractAddress) {
        a = MyContract(_contractAddress);
    }
}

Please explain what is happening in the above code. Thank You for your time.

1 Answer 1

1

a = MyContract(_contractAddress); will create a reference to the contract MyContract. Doing so allows you to call public functions of that contract.

Now you can do a.whateverFunctionAHas() which will call the function on the contract at the address.

2
  • What is _contractAddress here? Is it the address where MyContract is deployed?
    – sushantmit
    Dec 28, 2017 at 5:27
  • Yes, that’s correct. Dec 28, 2017 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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