Code. Books. Outdoors.

Error CS0012: Unable to generate a temporary class

I received an error when serializing a class to XML:

Unable to generate a temporary class (result=1).
error CS0012: The type 'MyType' is defined in an assembly that is not referenced. You must add a reference to assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=123412341234'.

Searching the web seemed to indicate that marking fields or properties of the class as non-serialized or adding a reference to the assembly containing the type would correct the problem. The odd thing is, MyType wasn’t part of the class being serialized; there were no fields or properties of MyType within the class!

Fortunately, I knew that it was working before I made some changes this morning. I had added the following:

I don’t have a definitive answer as to why this is the case, but I suspect that it’s due to class visibility at the time the serialization is done. Serialization works through reflection (hence why it’s controlled through decoration with attributes). I suspect with an implicit operator that .NET assumes MyType could be implicitly serialized instead of MySerializedClass so it wants to enumerate the FieldInfo and PropertyInfo on MyType. With an explicit operator it knows that case will never occur at runtime, as the conversion must be specified at compile time. Or, using a visible assembly for MyType allows that enumeration.

The mechanics are probably that it does Activator.CreateInstance(MyType) when serialization is needed, and if the public constructor for MyType isn’t known, that’s the underlying reason for the error.

I’ve seen some other weird things with implicit operators (see my later post on precedence) that make me think that implicit operators get a bizarre sort of pseudo-equality in .NET; i.e., if there is implicit operator TypeA(TypeB), then it thinks that it can use TypeB in the place of TypeA. I suspect that if TypeA implements InterfaceA, TypeB is implicitly convertible from TypeA, and TypeA and TypeB are different assemblies, calling a method of InterfaceA in TypeA will give a similar error message.

Just a hunch, so it could be wrong, but it makes sense (sort of) to me.

Well, that’s a solution to change to explicit operator, but for me wasn’t acceptable.

Adding and [XmlInclude(typeof(ProblematicType)] on top of your serialized class can also resolves the problem, but, i guess you have to make two implicit operators (TypeA -> ProblematicType and ProblematicType -> TypeA)

It seemed extremely difficult to solve my problem, but finally i found your post, thnx.

I also introduced some implicit operators in one of my serialized classes referring to the problematic class. The assembly of the problematic class was referenced from all of my projects, so it looked totally controversial.