TypeDescriptor replacement in PCL

383 views Asked by At

TypeDescriptor.GetConverter(Type) is a very convientent way to serialize/deserialize lots of built-in data types to/from strings:

object original = ...;

string serialized = TypeDescriptor.GetConverter(t).ConvertToInvariantString(original);
object deserialized = TypeDescriptor.GetConverter(t).ConvertFromInvariantString(serialized);

Unfortunately, TypeDescriptor is not available in portable class libraries.

Is there a canonical replacement or do we have to go back to huge switch statements?

3

There are 3 answers

3
Salah Akbari On

You can not use TypeDescriptor in PCL projects because it is not built as a PCL and it is not cross platform. The TypeDescriptor is unavailable in PCL projects and it is not listed here.

The following assemblies are available within a Portable Class Library project:

mscorlib.dll

System.dll

System.Core.dll

System.Xml.dll

System.ComponentModel.Composition.dll

System.Net.dll

System.Runtime.Serialization.dll

System.ServiceModel.dll

System.Xml.Serialization.dll

System.Windows.dll (from Silverlight)

1
Heinzi On

TypeDescriptor is not available in PCLs, but it might be available on the actual client using the PCL.

This is the workaround I used to inject the Mono TypeDescriptor from a Xamarin Android project:

PCL:

public interface IPclWorkaround
{
    ConvertFromInvariantString(Type type, string s);
}

Xamarin Android:

[assembly: Dependency(typeof(PclWorkaround))]

class PclWorkaround : IPclWorkaround
{
    public object ConvertFromInvariantString(Type type, string s)
    {
        return TypeDescriptor.GetConverter(type).ConvertFromInvariantString(s);
    }
}

Usage in PCL:

var myObject = DependencyService.Get<IPclWorkaround>.ConvertFromInvariantString(type, myString);
0
Shimmy Weitzhandler On

FWIW, fortunately this is covered in .NET Standard 2.0.
.Net Standard 1.4 is already accessible using XF (Xamarin Forms). Hopefully, real soon (vNext), with the official release of 2.0, Mono and in turn XF.iOS, XF.Droid, XF.Mac and UWP, will also join the party and all those missing APIs will be available in XF, as seen in this table.