Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type comparison not returning expected result

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.

like image 306
James South Avatar asked Jun 17 '26 18:06

James South


1 Answers

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)
{
   ...
}
like image 57
Ani Avatar answered Jun 19 '26 07:06

Ani