String.Length is throwing object reference not set to an instance of the object error

String.Length is throwing object reference not set to an instance of the object error

I have a string variable which is null.

Since it’s null it’s throwing the object reference not set to an instance of the object error. But how can I get the value as “0” if the string value is null.

Eg: nameStr = “”
nameStr.Length — this is throwing the error

In C#, if a string is null, attempting to reference a method or property such as .Length on it will throw a NullReferenceException (the “object reference not set to an instance of an object” error), because null means “does not exist”, so there’s nothing on which to execute a method or property.

However, there is a way to avoid this exception:

Add an Assign activity for a System.Int32 variable with value If(nameStr IsNot Nothing, nameStr.Length, 0)

If the value is not Nothing, it will display the length of the string, otherwise it will display 0.

@marian.platonov

just a follow up question.

You are saying “nameStr IsNot Nothing”, how is that possible? It should be “nameStr Is Nothing” right? What am I missing here? But your statement worked.

Here is how this If() function works:

If(condition, true_part, false_part)

  • condition: This part is checked first. If it turns out to be True, then the true_part is returned, otherwise the false_part is returned.
  • true_part: This part is returned if the condition is True.
  • false_part: This part is returned if the condition is False.

In the specific case, the If() function is checking to see if nameStr is not null:

  • If nameStr is not null, it returns the Length of nameStr.
  • If nameStr is null, it returns 0.

@marian.platonov - ty very much for the explanation. That makes sense to me now.

1 Like

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