CommunicationException was unhandled by user code / There was an error while trying to serialize parameter http://tempuri.org/:serviceList
Error Code:
There was an error while trying to serialize parameter http://tempuri.org/:serviceList. The InnerException message was 'Enum value '0' is invalid for type 'Project.Common.DataContracts.Contract.ContractTypes' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.'. Please see InnerException for more details.
Why:
You are using Windows Communication Foundation (WCF), without WCF, you will not have this issue. This is cased by a serialisation issue introduced by WCF if one of the properties in the object that you were trying to send back to the service is not defined.
Example:
Assume that the ContractType is one of the properties in ObjectType,
====ContractType.cs====
using System.Runtime.Serialization;
namespace Project.Common.DataContracts.Contract
{
[DataContract]
public enum ContractType
{
[EnumMember]
Person = 1,
[EnumMember]
Company = 2
}
}
When trying the send an instance of ObjectType back to the WCF service, all the properties of ObjectType, in this example, ContractType, should be initialized.
For example, if one of the properties in the instance is not initialized, the default value will be set to 0 (zero) if it is an enum type.
In this case, since the ContractType does not contain o (zero), and if you forget to intialize its ContractType, you will receive a similar error above.
Solution:
The solution is pretty simple, just keep a good programming habit, initialize everything before using it, and when defining the properties, the definitions should contain the fallback values, such as "null" and "0" (zero).