I have 2 independent classes A and B and I have a Storage class which manages the storage of objects of type A and B.
I am trying to abstract the code that does the Store of A and B, however I am stuck due to List covariance I could not assign List<object> objList = new List<A>(); in the following code.
[DataContract]
public class A {
public int UID;
}
[DataContract]
public class B {
public int UID;
}
public class Storage {
public void Store(A a) {
List<A> aList = ReadA();
if (aList == null) {
aList = new List<A>();
}
aList.Add(a);
WriteNodes(aList);
}
public void StoreB(B b) {
List<B> bList = ReadB();
if (bList == null) {
bList = new List<B>();
}
bList.Add(b);
WriteNodes(bList);
}
public List<A> ReadA() {
//deserializes from aFileName and returns List<A>
}
public List<B> ReadB() {
//deserializes from bFileName adn returns List<B>
}
private static void WriteNodes<T>(List<T> nodeList) {
FileStream fs = new FileStream(aFileName, FileMode.Create);
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
DataContractSerializer ser =
new DataContractSerializer(typeof(List<T>));
ser.WriteObject(writer, nodeList);
writer.Close();
fs.Close();
}
}
If you look at StoreA and StoreB methods they have a generic pattern except for the type that is used. ReadA and ReadB are no problem I could just take the type as another parameter and create a single function Read.
So is it possible to create an abstraction for Store so I don’t end up with StoreA and StoreB methods?
Yes, you can do it by introducing common interface for items to be sotred and extract item type into enum.
STORAGE
Abstract Storage Item type (more generic solution):