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!)