[S.R.Serialization] additional type check for collection serialization is also needed.
[mono.git] / mcs / class / System.Runtime.Serialization / ReferenceSources / XmlFormatWriterGenerator_static.cs
index ca5dfcf6c2274401209bf4b3f3ee8fdb050adcdd..0ed9000d2cebbffe484ce0110a42a67d0c5d4f21 100644 (file)
@@ -169,6 +169,13 @@ namespace System.Runtime.Serialization
                        {
                                Type itemType = collectionContract.ItemType;
                                int i;
+
+                               // This check does not exist in the original dynamic code,
+                               // but there is no other way to check type mismatch.
+                               // CollectionSerialization.ArrayContract() shows that it is required.
+                               if (objLocal.GetType ().GetElementType () != itemType)
+                                       throw new InvalidCastException (string.Format ("Cannot cast array of {0} to array of {1}", objLocal.GetType ().GetElementType (), itemType));
+
                                ctx.IncrementArrayCount (writer, (Array) objLocal);
 
                                if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, () => objLocal, itemName, itemNamespace))
@@ -188,6 +195,12 @@ namespace System.Runtime.Serialization
                        }
                        else
                        {
+                               // This check does not exist in the original dynamic code,
+                               // but there is no other way to check type mismatch.
+                               // CollectionSerialization.ArrayContract() shows that it is required.
+                               if (!collectionContract.UnderlyingType.IsAssignableFrom (objLocal.GetType ()))
+                                       throw new InvalidCastException (string.Format ("Cannot cast {0} to {1}", objLocal.GetType (), collectionContract.UnderlyingType));
+                               
                                MethodInfo incrementCollectionCountMethod = null;
                                switch (collectionContract.Kind)
                                {