MattyMatt
MattyMatt

Reputation: 640

C# Making methods more generic for re-use, is there a better way?

I guess this isn't much of a question, because what I've coded by more or less guessing, works. I'm obviously not using the right terms on google, because outside of the generic type part, I've come up and had to test the rest to confirm functionality.

I went from methods like this:

    private void SaveHw()
    {
        XmlSerializer xml = new XmlSerializer(typeof(List<Hardware>));
        try
        {
            using (StreamWriter sw = new StreamWriter(fileHw))
            {
                xml.Serialize(sw, lstHw);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to update local hardware XML.\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

to this:

    private void SaveList<T>(List<T> lst, string file)
    {
        XmlSerializer xml = new XmlSerializer(typeof(List<T>));
        try
        {
            using (StreamWriter sw = new StreamWriter(file))
            {
                xml.Serialize(sw, lst);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed to update local hardware XML.\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

and this

        private List<T> LoadList<T>(List<T> lst, string file)
    {
        // don't bother if the file does not exist.
        if (File.Exists(file))
        {
            // straight forward
            XmlSerializer xml = new XmlSerializer(typeof(List<T>));
            try
            {
                using (StreamReader sr = new StreamReader(file))
                {
                    return (List<T>)xml.Deserialize(sr);
                }
            }
            catch
            {
                MessageBox.Show("Failed to load local hardware XML.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        return new List<T>();
    }

And other slight generic variations to manipulate some of the data I know will be present in any of the lists used.

My question is, are there better ways? These aren't big custom things, so they are just structs in a list. This data is supposed to eventually be a db, so I didn't want to use classes.

Upvotes: 3

Views: 91

Answers (1)

Shachaf.Gortler
Shachaf.Gortler

Reputation: 5735

The only thing I would add to make the class more extendable, is a more generic way of input loading\saving, using a data load interface as input to the load\save functions

private IEnumerable<T> LoadData<T>(IEnumerable<T> list, IDataLoader loader)
{ 
     ...
}

interface IDataLoader 
{
      StreamReader Load(...);
      StreamWriter Save(...); 
}

and a a more concurrent class for file input

class FileDataLoader : IDataLoader 
{
     ...
}

this way if in the future for example a DB is added it would not require any changes to LoadData

Upvotes: 3

Related Questions