Say I have one string String strId = 001xa000003DIlo
and I want to typecast it to an Id. So I have two options to do so:
Id idVal = (Id)strId;
Id idVal = Id.valueOf(strId);
Which is the best way to achieve this purpose?
What exactly is the difference between these two approaches?
Is the difference same for typecasting a String
, Decimal
or any other datatype?
Best Answer
The first is casting. The second is calling a static method on the
Id
class.One major advantage of the former is that it is more null safe.
One advantage of the latter is that you can one-line more of your code by calling instance methods on the cast result. You can get one-liners by adding some parentheses to the casting approach, though some might object on stylistic grounds. I find it a little more visually confusing.
The above pros/cons are independent of type, so you can carry these conclusions over to
String
,Decimal
, etc.