Can I somehow refactor this into one class? Some things are common here like Metadata property.
public class Resource<TEntity>
{
public TEntity Data { get; set; }
public Dictionary<string, string> Metadata { get; set; }
public Resource(TEntity data)
{
Data = data;
}
}
public class ResourceCollection<TEntity>
{
public ICollection<TEntity> Data { get; set; }
public Dictionary<string, string> Metadata { get; set; }
public int Count { get; set; }
public ResourceCollection(ICollection<TEntity> data)
{
Data = data;
Count = data.Count;
}
}
Is this possible to make interface that expects either ICollection<TEntity>
or TEntity
alone?
This wrapper class is used for serialization it simply acts as a wrapper, but still I have some doubts about it that it could be done better
I also came up with this:
public class Resource<T>
{
public T Data { get; set; }
[JsonExtensionData]
public Dictionary<string, object> Metadata { get; set; } = new Dictionary<string, object>();
public Resource(T data)
{
Data = data;
if (data is ICollection collection)
{
Metadata["count"] = collection.Count;
}
}
}
ResourceCollection<Foo>
overResource<List<Foo>>
? (I'm not implying that there is no reason to do so, but I assume that you've omitted the code that would answer these questions). For CodeReview.SE, you should really be posting the full code, including usage (and and explanation of what you hope to achieve with the code) \$\endgroup\$Count
of a resource be when it's not an IEnumerable? Fixed value 1? If you're asking to unify these classes, then you're obviously going to have aCount
for all cases (whether it's a collection or not). You seem to be focusing on how to do it, but you still haven't actually shown a justification for why you need to do it, which should be the first step here. \$\endgroup\$rc.Metadata = null
? And why do you need aCount
property if you already have anICollection
? If you do need it, why doesn't it just returnData.Count
, as Nikita's answer does? \$\endgroup\$