1

I m populating data for different entities into set of lists using generic lists as follows :

List<Foo> foos ..
List<Bar> bars ..

I need to write these lists to a file, i do have a util method to get the values of properties etc. using reflection.

What i want to do is: using a single method to write these into files such as:

 void writeToFile(a generic list)
 {
  //Which i will write to file here.
 }

How can i do this?

I want to be able to call :

writeToFile(bars);
writeToFile(foos);
1
  • It is really good to make a generic method like all the answers do. But I want to mention that since 2012, there are covariant interfaces such as IReadOnlyList<out T>. Here "out" means the interface is covariant in T. So if you make a method WriteToFile(IReadOnlyList<object> list) { /* ... */ } then it will allow both a List<Foo> and a List<Bar> as long as Foo and Bar are reference types. Of course, you could use IReadOnlyList<IYourWritable> list or similar also. Commented Apr 15, 2023 at 14:33

4 Answers 4

10
void writeToFile<T>(List<T> list)
{
    // Do the writing
}
Sign up to request clarification or add additional context in comments.

Comments

5

You can use generics to allow the caller to specify the expected type the list contains.

void writeToFile<T>(IList<T> list)
{
    ...
}

1 Comment

Hmm thats what you get for loading a question and not replying for a while - Jacob got there first.
3

Probably something like...

private void WriteToFile<T>(
  IEnumerable<T> elementsToWrite,
  Func<T, string> convertElementToString) {
  foreach (var element in elementsToWrite)
  {
    var stringRepresentation = convertElementToString(element);
    // do whatever other list-stuff you need to do
  }
}

// called like so...
WriteToFile(listOfFoo, foo => foo.FP1 + ", " + foo.FP2 + " = " foo.FP3);
WriteToFile(listOfBar, bar => bar.BP1 +"/"+ bar.BP2 + "[@x='" + bar.BP3 + "']");

...or you could try something like...

private void WriteToFile<T>(
  IEnumerable<T> elementsToWrite,
  Action<T, TextWriter> writeElement) {
  var writer = ...;

  foreach (var element in elementsToWrite)
  {
    // do whatever you do before you write an element
    writeElement(element, writer);
    // do whatever you do after you write an element
  }
}

// called like so...
WriteToFile(listOfFoo, (foo, writer) =>
  writer.Write("{0}, {1} = {2}", foo.FP1, foo.FP2, foo.FP3));
WriteToFile(listOfBar, (bar, writer) =>
  writer.Write("{0}/{1}[@x='{2}']", bar.BP1, bar.BP2, bar.BP3));

...or whatever... you get the idea.

Comments

1

You should look into the topic of serialization. There is are some articles out there about dealing with generic types.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.