I’m playing with the following code:
[ServiceContract]
public interface IUserAccountService
{
[OperationContract]
UserAccountResponse CreateNewUserAccount(UserAccountRequest userAccountRequest);
}
public abstract class BaseResponse
{
public bool Success { get; set; }
public string Message { get; set; }
}
public class UserAccountResponse : BaseResponse
{
public int NewUserId { get; set; }
}
My questions are:
- Do I need to add the DataContract attribute to both the abstract class and the subclass?
- If the abstract class does not need the DataContract attribute, can I add the DataMember attribure to its properties?
If you want items in the base class to be serialized, then you must apply DataContract to the base class and apply DataMember to those items that are to be serialized in the base class. However, if you do not want anything in the base class to be serialized, then you shouldn’t need to specify DataContract on the base class.
From the MSDN documentation:
“When you apply the DataContractAttribute to a base class, the derived types do not inherit the attribute or the behavior. However, if a derived type has a data contract, the data members of the base class are serialized. However, you must apply the DataMemberAttribute to new members in a derived class to make them serializable.”