سؤال

using "Replace" on the string clientNameStr causes an "Object Reference Not Found" error.

// Get client name
clientName = currentUser.GetValue("ClientName");
string clientNameStr = (string)clientName;
string clientURLStr = string.Empty;
clientURLStr = clientNameStr.Replace(' ', '-');
// clientURLStr = "ST9215-Stanic-Parts-Ltd";

If I substitute in the commented out string (and comment out the existing one) it works fine, so it must be something to do with the replace function, but what? Have tried it with both " and ' quote marks, to the same result.

Any help would be greatly appreciated.

Thanks, Oli.

هل كانت مفيدة؟

المحلول

That basically shows that currentUser.GetValue("ClientName") is returning a null reference1. We can't tell what currentUser.GetValue("ClientName") does, but there are two options:

  • It's correctly returning null, and you should handle that
  • It shouldn't return null, and you need to fix it (possibly to throw an exception if it encounters this situation)

1 It's possible that it's returning a non-null reference and using a user-defined conversion to string in the next line which returns null - but unlikely. We can't tell for sure because we don't know the type of the clientName .

نصائح أخرى

Probably clientName (and thus clientNameStr) is null. You cannot call methods on the null object, even if you know that it should be a string.

It's possible that currentUser.GetValue("ClientName") is returning null, thus throwing an error when trying to execute the Replace.

Better coding would be

clientName = currentUser.GetValue("ClientName");
string clientNameStr = clientName ?? "";
string clientURLStr = clientNameStr.Replace(' ', '-');
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top