Keith Adler
Keith Adler

Reputation: 21178

Cannot use ternary operator in LINQ query

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?

Upvotes: 3

Views: 6002

Answers (3)

Marko
Marko

Reputation: 5552

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

Upvotes: 1

Adam Robinson
Adam Robinson

Reputation: 185643

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

Upvotes: 1

SLaks
SLaks

Reputation: 887509

d.SourceType is null.

You should call

(String.IsNullOrEmpty(d.SourceType) ? ", " + d.SourceType : string.Empty)

Upvotes: 8

Related Questions