Assume that I have an Array of objects in C#, and I want to write it to a file in CSV format.
Assume that each object has a ToString() method, which is what I want to be printed.
Currently I am using this code:
public static void dumpArray(Array arr, string fileName)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileName))
{
foreach (Object obj in arr)
{
file.Write(obj.ToString()+",");
}
}
}
Is there anything built in C# framework, or do you think that there is a better way?
You could change your method to use C# Generics and use descriptive function and variable names. This essentially results in the same behaviour except that boxing is avoided for value types.
Edit: to do the same with jagged Arrays (assuming they only ever contain one level of nesting) you could use this overload (not recommended, see below!):
EDIT – Regarding duplication:
The above solution is, of course, sub-optimal in that it only works in a some specific scenarios (where we have exactly one level of nesting). Unfortunately, if refactor our code, we have to stop using generics because our input array might now contain elements of Type
Tor of TypeT[]. Therefore, we come up with the following code, which is the preferred solution because, although it reintroduces boxing, is more readable, less redundant, and works for a wider range of scenarios: