Difference between .toString and convert.toString()

Hi All!
Good Day!

I have created generic value “Sample”, and I assign that value to nothing. while converting that generic value to string, I’m facing the issue

Sample.toString is working perfectly
but while using Convert.toString(Sample), Im getting the error, attached below

please let me know the difference between .tostring and convert.toString, and in which instance we need to use these methods to convert the string

Thanks

it is about as you pass nothing as variable content
grafik

nothing cannot be derrived to the accepted / expected datatypes

Convert.TosString Docu:

Hi Peter,

Thanks for the reply,
I have tried the assigning the sample variable from generic to object type as per the documentation. .tostring method not able to convert the object type of null value to string , but convert.tostring accepts a null value, and it executed successfully

this is different
whenever something is nothing, we cannot call / execute methods from this null object

But lets go one step back, what is your overall goal? Handling possible null values?

We can use the isNothing(yourVar) method to setup defensive access

Hi @Gokula_Krishnan_S

→ Use .ToString() when you are sure that the object is not null

→ Use Convert.ToString() when there’s a possibility that the object might be null, and you want to avoid NullReferenceException while safely converting the object to a string.

1 Like

Just to summarize it and get bound on your initial case, where sample was set to Generic Value DataType


Convert.ToString(Sample) will fail as it is not matching the method signature in a clear resolved way

Sample.ToString(), fails as Sample is nothing / null and therefore we got the null reference exception

When changing it to Sample | DataType: Object = nothing then Convert.ToString() is not leading to the BC30521
But same as above will fail on Sample.ToString() as Sample is null

1 Like

Actually, im extracting the specific content from the queue data.so from queue the data might be blank or null, in worst case. while assigning the data to the string variable, .tostring throws object reference error and convert.to string works perfect though it is null. Later im checking the conditions to evaluate whether any of the extracted data content is null, if it is null, im throwing the business exception

Thanks Pradeep!!! for the suggestion

1 Like

Check if SpecificContent is available:
isNothing(myQueueItem.SpecificContent)

Check if SpecificContent has a particular key:
myQueueItem.SpecificContent.ContainsKey(“myKey)”

And then you can handle as mentioned above with Convert.ToString(myQueueItem.SpecificContent("myKey")

or with any other available conversion options

1 Like

Thanks Peter!! for the suggestion

And also:

Once prechecks from above were passed:
isNothing(myQueueItem.SpecificContent("myKey"))

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.