How to convert Id to String in Apex? [duplicate]

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?

Answer

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.

Attribution
Source : Link , Question Author : Bradley Thomas , Answer Author : BradByte

Leave a Comment