I previously asked the question How to save/restore serializable object to/from file? that solution works great when I know what type of object I will be saving.
It will be nice if I could save an object of unknown type.
Anyways I am looking to do something like:
[Serializable]
MyCustomClass
{
// properties. I don't know which properties this class has. I might pass a different class.
}
public void saveObjectInComputer(object obj, string pathWhereToSaveObject)
{
// code
}
public object deserializeObject(string pathWhereObjectIsLocated)
{
// code to retrive object
// ...
return object;
}
static void Main(string[] args)
{
List<MyCustomClass> myList = new List<MyCustomClass>();
myList.add(new MyCustomClass { "properties go here" } );
saveObjectInComputer(myList, @"C:\Temp\object.txt");
// code
// Later it will be nice if I could retrive the object
object a = deserializeObject(@"C:\Temp\object.txt");
// then cast a to List<MyCustomClass>
}
And later if I construct a list of cars or a list of people I could use the same method instead of constructing a new method for each. Moreover later I know that the method I am looking for will return an object and I could cast that object to the type that I am currently working with.
You cannot serialize an object that has not been marked with the Serializable attribute easily, so the short answer is no.
If you’re willing to step into moderately difficult code, you could use reflection and devise a custom format to save states with, using exceptions for things like indexed properties, etc.. You might as well just not, though.