How to convert Id to String in Apex?

  • I've been searching the documentation for this, without much luck so far. In particular I'd like to convert an Id to a 18-char string, and ideally read about that in documentation to verify its the recommended approach.

    I've seen various approaches including

    String str = '' + someId;
    

    Is this the same as

    String str = (String)someId; 
    

    I've also seen

    String str = String.valueOf(someId);
    

    However when I tried that I got 15-char strings! Why is that?!

    What is the recommended approach to always guarantee an 18-char string from an Id?

  • You need to get it as Id.valueOf('someId'). This will return the 18 char id. See below:

    String strId = Id.valueOf('yourId');
    

    This will store the 18 char Id in String format.

    I don't want an Id result, I want an 18-char string as the result

    It will work with strings.. updated the answer.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used