0

Here is my code:

public static class SerializationUtil
{
    public static string Serialize(object obj)
    {
        if (obj == null)
            return string.Empty;

        StringWriter writer = new StringWriter();
        new System.Web.UI.LosFormatter().Serialize(writer, obj);
        return writer.ToString();
    }

    public static object Deserialize(string data)
    {
        if (data == null)
            return null;
        return (new System.Web.UI.LosFormatter()).Deserialize(data);
    }
}

The problem I am having is: When I call the serialize method if the obj is null it throws an error. So i would like to check if the obj value is null or not. The code I have i place now does not work as when the obj value is checked its never null.

Resolved:

See my post in answers

6
  • 3
    Exactly where is the exception thrown? Do you have the stack trace from the exception? Commented Aug 21, 2010 at 5:36
  • it is thrown at new System.Web.UI.LosFormatter().Serialize(writer, obj); Commented Aug 21, 2010 at 5:38
  • Please post the exact error message. Commented Aug 21, 2010 at 5:41
  • Can you also put in the exception details including the stack trace in the post as Fredrik suggested? Commented Aug 21, 2010 at 5:41
  • Unrelated to your question, but since Serialize generates an empty string instead of null, perhaps Deserialize should accept an empty string in addition to null. Commented Aug 21, 2010 at 6:32

2 Answers 2

2

OK, I have figured it out. I looked at the details of the exception and it expected the object class to be serializable. I made the class serializable and it worked

using System;

[Serializable]  //the missing piece
public class RegisterFormData
{
    public string username { get; set; }
    public string pass1 { get; set; }
    public string pass2 { get; set; }
    public string email { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

you know, I was going to suggest that in the comments, and then thougth it couldn't possibly be because of that, could it?
1

I really don't think that what you're describing is possible. If you've checked that obj is not null only a few lines above, then it is not null. If you're getting a NullReferenceException it is likely due to something else being null, possibly within the Serialize method itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.