1

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());      
      }
    }
  • Hi, the implement is in C#, but you can help me in pseudo code. I want to organize the code can be reuse. With my approach, it needs rewrite dumpToFile() to write one more field :( – Sanna Jo Aug 13 '16 at 19:03
  • 1
    @CandiedOrange: I think one can look at this question more gracefully and see it as problem of not having understood how to utilize function overriding in an inheritance hierarchy - that way, I guess it becomes a design question. – Doc Brown Aug 13 '16 at 20:18
  • @DocBrown very well – candied_orange Aug 13 '16 at 21:48
4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.