Search code examples
c#datacontract.net-standard.net-standard-1.4

NetStandard 1.4 does not allow decorating class with [DataContract]


When I try to decorate a class with [DataContract] in a .NETStandard 1.4 project

[DataContract]
[KnownType(typeof(SingleSensorEvent))]
[KnownType(typeof(BatchSensorEvent))]
public abstract class WebItemBase
{
    // details left out
}

I get the following compile error

1>WebItemBase.cs(7,6,7,18): error CS0653: Cannot apply attribute class 'DataContract' because it is abstract

1>WebItemBase.cs(8,6,8,15): error CS0012: The type 'Attribute' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Is there a way to use data contracts in NETStandard 1.4?


Solution

  • You'll need to add a reference to the System.Runtime.Serialization.Primitives NuGet package to make use of DataContractAttribute. It will be available automatically in netstandard2.0:

    dotnet add package System.Runtime.Serialization.Primitives