views:

85

answers:

3

I am using the following code to compare types so that a DataContractSerializer will re-initialize with the correct type if necessary.

    private void InitializeSerializer(Type type)
    {
        if (this.serializer == null)
        {
            this.serializer = new DataContractSerializer(type);
            this.typeToSerialize = type;
        }
        else
        {
            if (this.typeToSerialize != null)
            {
                if (this.typeToSerialize.GetType() != type.GetType())
                {
                    this.serializer = new DataContractSerializer(type);
                    this.typeToSerialize = type;
                }
            }
        }
    }

For some reason when I compare the two types the result is always true and I never enter the final 'if' statement and re-initialize my serialiser.

I can set a break point at the comparison and clearly see that the two types are List<Host> (this.typeToSerialize.GetType()) and Post (type.GetType())

Both Host and Post share a common ancestor but that shouldn't be affecting the result.

+6  A: 

You are calling GetType() on a System.Type. This will return a System.Type object that describes System.Type itself.

This makes the code

if (this.typeToSerialize.GetType() != type.GetType())
{
   ...
}

equivalent to:

if(typeof(System.Type) != typeof(System.Type)) // Always false
{
   ... // Never enters here
}

I'm guessing what you really mean to be doing is:

if(typeToSerialize != type)
{
   ...
}
Ani
Indeed, if you lose the two .GetType() calls in the condition it should work correctly.
Joachim VR
Brilliant. I knew it was something simple. Thanks for the underlying explanation too.
James South
+2  A: 
if (this.typeToSerialize != type)

looks more appropriate

vc 74
+3  A: 

It looks as though you are comparing the types of two Type objects. I think you would need to compare the type objects themselves.

this.typeToSerialize != type

Both this.typeToSerialize.GetType() and type.GetType() will return typeof(Type) (the same object).

Steve