Portable class library: recommended replacement for [Serializable]
Solution 1
Portable Class Libraries (PCLs) now officially deprecated [16 August 2017]
If you’re sharing code between different .NET implementations today, you’re probably aware of Portable Class Libraries (PCLs). With the release of .NET Standard 2.0, we’re now officially deprecating PCLs and you should move your projects to .NET Standard.
Source: Announcing .NET Standard 2.0
Portable Class Library (PCL) now available on all platforms [14 Oct 2013]
Prior to today’s release, there was a license restriction with the PCL reference assemblies which meant they could only be used on Windows. With today’s release we are announcing a new standalone release of the PCL reference assemblies with a license that allows it to be used on any platform – including non-Microsoft ones. This enables developers even more flexibility and to do great things with .NET.
Source: Portable Class Library (PCL) now available on all platforms
Download: Microsoft .NET Portable Library Reference Assemblies 4.6 RC
Just for the reference the allowed set of assemblies are:
mscorlib.dll
System.dll
System.Core.dll
System.Xml.dll
System.ComponentModel.Composition.dll (MEF)
System.Net.dll
System.Runtime.Serialization.dll
System.ServiceModel.dll
System.Xml.Serialization.dll
System.Windows.dll (from Silverlight)
As far as I know you need to mark the fields with DataMember attribute, and add the DataContract attribute.
UPDATE
Yes.
You can look how Json.NET portable class library solution is implemented. You can find the solution in the Source\Src\Newtonsoft.Json.Portable when you download the project from here Json.NET 4.5 Release 10 (source + binary).
Basically they are using an approach with a custom attribute provider
//don't use Serializable
#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE)
[Serializable]
#endif
//use custom provider
#if NETFX_CORE || PORTABLE
using ICustomAttributeProvider = Newtonsoft.Json.Utilities.CustomAttributeProvider;
#endif
And if project is PORTABLE
#if !PocketPC && !NET20
DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType);
if (dataContractAttribute != null)
return MemberSerialization.OptIn;
#endif
where OptIn description is:
/// <summary>
/// Only members must be marked with <see cref="JsonPropertyAttribute"/> or <see cref="DataMemberAttribute"/> are serialized.
/// This member serialization mode can also be set by marking the class with <see cref="DataContractAttribute"/>.
/// </summary>
OptIn,
Hope it helps.
UPDATE 2
Am I losing any abilities using [DataContract] instead of [Serializable], or will I still be able to do everything that [Serializable] supports?
You can do everything that Serializable supports except control over how the object is serialized outside of setting the name and the order.
Using DataContractSerializer has several benefits:
serialize anything decorated with a [DataMember]
even if it's not public visible
can't serialize anything unless you specifically tell it to ("opt-in")
you can define the order in which the elements are serialized using the [Order=]
attribute on the [DataMember]
doesn't require a parameterless constructor for deserialization
is 10% faster than XmlSerializer.
Read more here: XmlSerializer vs DataContractSerializer
Also for the reference:
DataContract
supports serialization of the following kinds of types in the default mode:
CLR built-in types
Byte array, DateTime, TimeSpan, GUID, Uri, XmlQualifiedName, XmlElement and XmlNode array
Enums
Types marked with DataContract or CollectionDataContract attribute
Types that implement IXmlSerializable
Arrays and Collection classes including List, Dictionary and Hashtable
Types marked with Serializable attribute including those that implement ISerializable
Types with none of the above attributes (POCO) but with a default constructor
Solution 2
One thing you could do to eliminate the clutter that the constant preprocessor directives causes is to push that off to one new SerializableAttribute
class and basically trick the compiler.
#if PORTABLE
namespace System
{
public class SerializableAttribute : Attribute
{
//this does nothing
}
}
#endif
Then just continue to decorate your classes with Serializable
as normal...
Solution 3
For .Net 4.6 and up the DataContract is no longer available to PCL. You need to add the Nuget package System.Runtime.Serialization.Primitives available here: https://www.nuget.org/packages/System.Runtime.Serialization.Primitives/
Note for actual serialisation you'll probably also need an implementation such as System.Runtime.Serialization.Json, System.Runtime.Serialization.Xml or a Newtonsoft.Json.
Related videos on Youtube
Anders Gustafsson
I am the owner of Cureos AB, a software development and consulting company located in Uppsala, Sweden. The company's main focus is in developing software for dose-response analysis and optimization of large patient treatment materials, primarily using the .NET framework. In my Ph.D. thesis I outlined a general optimization framework for radiation therapy, and I have developed numerous tools for radiotherapy optimization and dose-response modeling that have been integrated into different treatment planning systems.
Updated on July 09, 2022Comments
-
Anders Gustafsson almost 2 years
I am porting a .NET Framework C# class library to a Portable Class Library. One recurring problem is how to deal with classes decorated with the
[Serializable]
attribute, since this attribute is not part of the Portable Class Library subset. Serialization functionality in the Portable Class Library subset instead appears to be covered by DataContractAttribute.- To preserve as much of functionality as possible in the Portable Class Library, is it sufficient to replace
[Serializable]
with the[DataContract]
attribute (with the implication that all fields and properties subject to serialization would need to be decorated with[DataMember]
as well)? - What (if anything) will I not be able to do with this approach that I can do with
[Serializable]
applied? - Is there a less intrusive approach?
Given that
[DataContract]
and[DataMember]
are used, I am considering to change the code along the following lines. Are there any obvious flaws with this approach? Is there any way to formulate the same thing less verbose?#if PORTABLE [DataContract] #else [Serializable] #endif public class SerializableClass : SerializableBaseClass { ... #if !PORTABLE protected SerializableClass(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif ... #if PORTABLE [DataMember] #endif private Type1 _serializableField; #if PORTABLE [DataMember] #endif private Type2 SerializableProperty { get; set; } ... }
- To preserve as much of functionality as possible in the Portable Class Library, is it sufficient to replace
-
Anders Gustafsson over 11 yearsThanks! However, with this solution seriality functionality would be left out, right?
-
Anders Gustafsson over 11 yearsMy main concern is; would decoration with [DataContract] and [DataMember] be sufficient replacements for [Serializable]?
-
Anders Gustafsson over 11 yearsMany thanks for the informative update, I'll have a closer look at JSON. Am I losing any abilities using [DataContract] instead of [Serializable], or will I still be able to do everything that [Serializable] supports?
-
Display Name almost 10 yearsThis doesn't work — there is an exception like "Type *** is not marked as Serializable."
-
Barton about 9 yearsHmm... According to this comment forums.xamarin.com/discussion/comment/71885/#Comment_71885 in the post that linked me here, this should work, but I also get the "not marked" exception.
-
Barton about 9 yearsUsing Shim NuGet package fixes the first issue, but stock serialization doesn't play nicely with Azure .NET backend (non-clr types don't get serialized; just null arrives at the AMS side). So it looks like I'm after DataContractSerializer
-
Artiom about 8 yearsWorked for me. It's important
SerializableAttribute
to be inSystem
namespace -
Jay M over 6 yearsI didn't know you can do that! Saved me a bunch of time and made my life way easier! Thanks!