ComfortablyNumb
ComfortablyNumb

Reputation: 1456

Lightswitch NullReferenceException for String in C#

I am sure this is a case of basic ignorance, but I'm trying to test a database value using code behind in a Lightswitch project.

I'm checking if a varchar(MAX) value is null

if (Order.OrderNotes.Equals(null))
{
     do.something...
}

However, I get a NullReferenceException if the value is null. If a value is there I get no error. I've tried using .contains(null), .Length = 0, .ToString() = "" etc without luck. It seems that ints and dates work fine using Equals(null), but not it seems for a string.

Help!!

Upvotes: 2

Views: 838

Answers (3)

Yann Duran
Yann Duran

Reputation: 3879

In LightSwitch, to test if a nullable property has a value or not, you can use HasValue, so:

"if Order.OrderNotes.HasValue"

If you want the value if there is one, or the default value for the property type, you can use GetValueOrDefault:

"var value = Order.OrderNotes.GetValueOrDefault"

I agree wholeheartedly with Steve that you should be doing null checking on objects (such as Order) before trying to get a value from any of that object's properties.

Upvotes: 1

Nasreddine
Nasreddine

Reputation: 37908

Assuming you're calling this from a details screen where Order != null as @DeeMac pointed out. You can check that Order isn't null using the same code below :

if (Order.OrderNotes == null) 
{
    // do.something...
}

Upvotes: 3

Steve
Steve

Reputation: 216357

if OrderNotes is null, you can't call any method, properties or whatever using that instance

you should call

if (Order.OrderNotes == null) 

of course I assume that the var Order is not itself null, if you want to be absolutely sure you could change your test in this way

if (Order != null && Order.OrderNotes == null) 

Upvotes: 3

Related Questions