I have a few base, derived classes and need to dump their data to file. The difference is only a field, but I don’t know how to reuse code of base class. Sorry if noob question :p
Those classes look like this: (C# implement)
class Base{
public int id {get;set;}
public string field1 {get;set;}
}
class Child : Base{
public int onlyOneDifferentVariable {get;set;}
}
class ListBase{
public List<Base> data {get;set;}
public void dumpToFile() {
foreach (var item in data){
var newLine = string.Format("{0}|{1}",item.id,id.field1);
csv.Append(newLine);
}
File.WriteAllText(fileName, csv.ToString());
}
}
3
You can override the ToString
method in your classes Base
and Child
(I assume you already know that virtual method is defined in the object
class). For example, in Base
public override string ToString()
{
return string.Format("{0}|{1}",id,field1)
}
and in Child
:
public override string ToString()
{
return base.ToString() + string.Format("|{0}", onlyOneDifferentVariable);
}
That makes it possible to replace
var newLine = string.Format("{0}|{1}",item.id,id.field1);
by
var newLine = item.ToString();
If you need the ToString
method for other purposes, it is also possible to define your own virtual function in the class Base
and use that instead, this will make no substantial difference.
Consider also to use the existing serializing mechanisms of the .NET framework, there is typically no need to invent your own mechanism, except for learning purposes or for supporting specific file formats.