In Solidity, Is there any situation, when string is necessary? Please can u explain when I should use string instead of bytes or bytesN? Thanks!


In any standard ERC20-Token, for example, because that's what the ERC20 standard dictates:

  • function name() public view returns (string);
  • function symbol() public view returns (string);

If you use bytes32 instead (as implemented in some of the early ERC20 tokens deployed on mainnet), then you'll be violating the standard, and any application trying to interact with your token for displaying its name or symbol, will potentially break.

Here is how "twisted" it is to retrieve the symbol of a token which doesn't conform to the standard, and uses bytes32 symbol instead of string symbol (example using web3.js v1.2.1):

async function symbol(web3, token) {
    for (const type of ["string", "bytes32"]) {
        try {
            const contract = new web3.eth.Contract([{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":type}],"payable":false,"stateMutability":"view","type":"function"}], token);
            const symbol = await contract.methods.symbol().call();
            if (type.startsWith("bytes")) {
                const list = [];
                for (let i = 2; i < symbol.length; i += 2) {
                    const num = Number("0x" + symbol.slice(i, i + 2));
                    if (32 <= num && num <= 126)
                return String.fromCharCode(...list);
            return symbol;
        catch (error) {
    return token; // couldn't find any symbol, so return the token address instead
  • Name and symbol are optional though: 'OPTIONAL - This method can be used to improve usability, but interfaces and other contracts MUST NOT expect these values to be present.' Jun 29 '20 at 8:29
  • @Markus-soliditydeveloper.com: Yes, but they are nevertheless very common and very widely in use. I'll add a coding example to show how annoying it is for an application which expects to find them. Jun 29 '20 at 8:33
  • Agreed, but it's still standard-compliant to not have them. Jun 29 '20 at 8:43

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.