None
None

Reputation: 5670

Value = 'p.Value' threw an exception of type 'System.NullReferenceException'

In my umbraco website I got a code like this

 var  p = currentNode.GetProperty("ucc") as Property;
 if (p != null && !string.IsNullOrEmpty(p.Value.Trim()))
 mailCC = p.Value;

But it always throws an error like this

Value = 'p.Value' threw an exception of type 'System.NullReferenceException'

Note:I am certain that P.Value is note Null enter image description here

Upvotes: 2

Views: 1152

Answers (2)

Amit Rai Sharma
Amit Rai Sharma

Reputation: 4225

+1 to Goran Mottram for pointing out the reason and giving the right suggestion. You should always check for null before doing any method call.

Upvotes: 0

Goran Mottram
Goran Mottram

Reputation: 6304

Invoking the Trim() method on p.Value when it's null is throwing the error. In your code, this is happening before string.IsNullOrEmpty gets to perform its check.

Modifying your expression to the following should fix it.

Code:

var p = currentNode.GetProperty("ucc") as Property;
if (p != null && !string.IsNullOrWhiteSpace(p.Value))
    mailCC = p.Value

Reference:

String.IsNullOrWhiteSpace : Indicates whether a specified string is null, empty, or consists only of white-space characters.

Upvotes: 3

Related Questions