3

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?

Community
  • 1
  • 1
bas
  • 13,550
  • 20
  • 69
  • 146
  • You did something you should not have done to get errors like this. Whatever it was, always best to not force us to guess, be sure to undo that again. Instead you need to add a reference to a Nuget package, System.Runtime.Serialization v4.3.0. Beware that your project now might not port to every platform you had in mind, YMMV. – Hans Passant May 13 '17 at 08:45
  • @HansPassant moving the classes to a new project and adding your suggested nuget package works. My time is up for now, so I will dig a little deeper later. I guess I broke something in the project. Many many thanks for your pointers! If you drop it as answer I will accept it. – bas May 13 '17 at 09:10
  • @HansPassant, given that I try to use type X (any normal .NET type that would also be available in .NET Standard), can you tell me a sure way to figure out which .NET Standard *minimum* version I need to target to use it, as well as which nuget package to add a reference to? I found it really hard to grok this part of the .NET Standard when dealing with my own class libraries but I'm also pretty sure I don't know where to look. – Lasse V. Karlsen May 13 '17 at 18:45
  • @LasseVKarlsen use https://learn.microsoft.com/en-us/dotnet/api/?view=netstandard-2.0 the name of the Nuget package is the assembly name the class is in – Scott Chamberlain May 13 '17 at 19:16

1 Answers1

9

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
Martin Ullrich
  • 94,744
  • 25
  • 252
  • 217
  • I have added this package to my class library project but still its not working. giving one error after another..https://stackoverflow.com/questions/70108674/upgrading-class-library-project-to-net-standard-2-1-where-this-has-been-referen – Annie Nov 25 '21 at 10:24