Sergio Romero
Sergio Romero

Reputation: 6597

subclassing and data contracts

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:

  1. Do I need to add the DataContract attribute to both the abstract class and the subclass?
  2. If the abstract class does not need the DataContract attribute, can I add the DataMember attribure to its properties?

Upvotes: 1

Views: 1526

Answers (2)

softveda
softveda

Reputation: 11066

Yes you will have to use [DataContract] on both BaseResponse and UserAccountResponse. You will also have to use the [KnownType] attribute for every subclass as shown below.

[KnownType(typeof(UserAccountResponse))]
[DataContract]
public abstract class BaseResponse
{
...
}

Upvotes: 0

competent_tech
competent_tech

Reputation: 44931

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."

Upvotes: 1

Related Questions