views:

59

answers:

2

There's probably a very simple reason for this, but when hydrating an object I'm keep getting a "value cannot be null" exception:

public class MyObject
{
   public MyObject() {
    }  

    public virtual IList<MemberObject> MemberObjects { get; protected set; }              

    [JsonProperty] public virtual SubObject LastMemberObject {
        get { return MemberObjects.OrderByDescending(x => x.CreatedOn).FirstOrDefault() ?? null; }
    }
 }

When hydrating the object, if the MemberObjects is null, LastMemberObject throws a cannot be null exception. What's the deal?

A: 

If the object MemberObjects is null, you can't call any instance methods on it.

[JsonProperty]
public virtual SubObject LastMemberObject {
    get {
        return MemberObjects != null
           ? MemberObjects.OrderByDescending(x => x.CreatedOn).FirstOrDefault()
           : null; }
    }

Also, when you're calling the FirstOrDefault() method, this "default has to be specified as well.

MemberObjects
.OrderByDescending (x => x.CreatedOn)
.Default (something)
.FirstOrDefault ();
Developer Art
`OrderByDescending` isn't an instance method, it is an extension method defined in a static class.
Greg
A: 

If MemberObjects is null you will get this exception if you attempt to access a method or property such as OrderByDescending. Try this:

[JsonProperty] public virtual SubObject LastMemberObject {
        get { return MemberObjects != null? MemberObjects.OrderByDescending(x => x.CreatedOn).FirstOrDefault() : null; }
    }
Andy Rose
I knew it was simple! Thanks.
chum of chance