beardedmogul beardedmogul - 28 days ago 5
C# Question

Convert List<object> to class of Objects : List<object>

Is it possible to convert a

List<Document>
to a class of
Documents : List<Document>


For instance, I have a class that looks something like this:

public class Documents : List<Document>
{

}


But I need to convert my
List<Document>
to
Documents
.

(Lack of information on this leads me to believe it is either not possible, or I am gravely mis-using these objects.

Answer

Method #1

There is currently no default builtin way to cast List<Object> to Objects : List<object>, but instead you could kind of clone the list:

public static Documents CastToDocuments(this List<Document> docs)
{
    var toRet = new Documents();
    toRet.AddRange(docs);
    return toRet;
}

I do also highly suggest reading another question on SO that already asked Why not inherit from List<T>?

Method #2

I just got the idea, that you could add a private list inside your Documents class and implement basic list logic and a ToList() method:

/// <summary>
/// Represents a list of documents.
/// </summary>
public class Documents
{
    /// <summary>
    /// Initialises the private list of documents.
    /// </summary>
    public Documents()
    {
        _docs = new List<Document>();
    }

    /// <summary>
    /// Add a speified document.
    /// </summary>
    /// <param name="doc">This document will be added to the saved documents.</param>
    public void Add(Document doc)
    {
        _docs.Add(doc);
    }

    /// <summary>
    /// Remove a specific document.
    /// </summary>
    /// <param name="doc">This document will be removed from the saved documents.</param>
    public void Remove(Document doc)
    {
        _docs.Remove(doc);
    }

    /// <summary>
    /// Removes all saved documents.
    /// </summary>
    public void Clear()
    {
        _docs.Clear();
    }

    /// <summary>
    /// "Casts" this instance to a list of documents.
    /// </summary>
    /// <returns>Returns all documents inside a list.</returns>
    public List<Document> ToList() => _docs;

    /// <summary>
    /// A list of documents.
    /// </summary>
    private readonly List<Document> _docs;
}

This seems a bit nicer to use because of the following benefits:

  • A nice wrapper for Document
  • More security on the actual list
  • More control of the list
  • The ability to only implement methods, that you really need
  • (And if you need the features of a list, than you could still just return your secure list!)