Introduction:

In this blog we will see how to Convert IEnumerable to ReadOnlyCollection in C#.

What is IEnumerable in C#?

All non-generic collections that can be enumerated use IEnumerable as their underlying interface. GetEnumerator, the only method in it, returns an IEnumerator. IEnumerator exposes the Current property, MoveNext, and Reset methods, enabling it to iterate through the collection.

we can convert IEnumerable to REadOnlyCollection in C# usiing the code shown below 

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Plugin_practice
{
public static class ReadOnlyExtensions
{
internal static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T> collection)
{
ReadOnlyCollection<T> roc = collection as ReadOnlyCollection<T>;
if (roc == null)
{
if (collection == null)
{
roc = EmptyReadOnlyCollection<T>.Empty;
}
else
{
roc = new List<T>(collection).AsReadOnly();
}
}
return roc;
}

class EmptyReadOnlyCollection<T>
{
internal static readonly ReadOnlyCollection<T> Empty = new List<T>().AsReadOnly();
}
}
}

For any Help or Queries Contact us on info@crmonce.com or +918096556344