Search code examples
xamarinportable-class-library

.AsReadOnly() not included PCL despite it being listed as supported in MSDN


According to the MSDN the, .AsReadOnly() method is listed as being supported by the PCL but I'm not able to reference it on my Xamarin PCL.

Can anyone verify this? If so are there any alternatives to .AsReadOnly() equivalent?

https://msdn.microsoft.com/en-us/library/e78dcd75(v=vs.100).aspx

https://developer.xamarin.com/api/member/System.Collections.Generic.List%3CT%3E.AsReadOnly()/


Solution

  • List<T>.AsReadOnly() is only available in some PCL profiles. In particular, those profiles that target Windows 8/8.1 and Windows Phone 8.1 non-Silverlight (32, 111, 259, 328 etc.) will likely not include List<T>.AsReadOnly(), since this method is not available on those platforms.

    The simple workaround is to create the ReadOnlyCollection<T> via the constructor:

    List<T> list;
    var listToReadOnly = new ReadOnlyCollection<T>(list);
    

    If you want to keep your source code intact you can even implement an extension method to do the job. Just include the following method in a public static class:

    public static ReadOnlyCollection<T> AsReadOnly<T>(this List<T> list)
    {
        return new ReadOnlyCollection<T>(list);
    }