0

I seem to be having an issue deserializing a CookieContainer. It serializes fine, but when I deserialize I am getting the error Object reference not set to an instance of an object at this line below cookieJar = (CookieContainer)info.GetValue("cookieJar", cookieJar.GetType());.

But if I uncomment the line that creates a new cookie container, I don't get the error, and the serialized CookieContainer is deserialized.

The cookieJar property is a property of MySession class.

public MySession(SerializationInfo info, StreamingContext context)
{
    //cookieJar = new CookieContainer()
    cookieJar = (CookieContainer)info.GetValue("cookieJar", cookieJar.GetType());
    email = info.GetString("email");
    password = info.GetString("password");

    client = new HttpClient(new HttpClientHandler() { CookieContainer = cookieJar });
}

public void GetObjectData(SerializationInfo info, StreamingContext context)
{
    info.AddValue("cookieJar", cookieJar);
    info.AddValue("email", email);
    info.AddValue("password", password);
}

Why is this?

James Jeffery
  • 12,093
  • 19
  • 74
  • 108
  • have you checked if `cookieJar` is null before calling GetType() on it? – Jehof Oct 25 '13 at 09:12
  • 2
    All `NullReferenceException`s are the same: one or more of the objects you "dot into" (for example `info.GetValue()` or `cookieJar.GetTyp()`) are `null`. Put breakpoints, go debug. Instead of `cookieJar.GetType()` you could try using `typeof(CookieContainer)`. – CodeCaster Oct 25 '13 at 09:19

1 Answers1

0

I think the variable cookieJar is null in your case so that the call GetType() will result in the NullReferenceException. You should change the codeline to the following to avoid the exception.

cookieJar = (CookieContainer)info.GetValue("cookieJar", typeOf(CookieContainer));

Jehof
  • 34,674
  • 10
  • 123
  • 155
  • No it is not null, because when I create an instance of `CookieContainer` prior to deserializing the CookieContainer it works fine and the CookieCollection is present. – James Jeffery Oct 25 '13 at 09:16
  • Oh wait. You're correct. What the fudge. Confused now. – James Jeffery Oct 25 '13 at 09:17
  • @JamesJeffery There can only be 2 things null at this line. The `SerializationInfo` you get passed to the constructor or the variable `cookieJar` and i think that you will not get a null value for SerializationInfo. – Jehof Oct 25 '13 at 09:19