tags:

views:

124

answers:

3

I can't figure out why I get a Object reference not set to an instance of an object. error if I use a ternary operator in my LINQ query.

var courses = from d in somesource
                          orderby d.SourceName, d.SourceType
                          select new
                          {
                              ID = d.InternalCode,
                              Name = string.Format("{0} - {1}{2}", d.InternalCode, d.SourceName, (d.SourceType.Length > 0 ? ", " + d.SourceType : string.Empty))
                          };

Any thoughts?

+7  A: 

d.SourceType is null.

You should call

(String.IsNullOrEmpty(d.SourceType) ? ", " + d.SourceType : string.Empty)
SLaks
You are correct. It turns out that even though it's a string it comes back null if empty. Thanks. I will select you as the correct answer once it allows me. I've upvoted similar answers.
Nissan Fan
+1  A: 

You're checking the Length property of SourceType, which could be null.

Adam Robinson
+1  A: 

Maybe SourceType is null, so you get exception on d.SourceType.Length.

Marko