A Reflection based settings class in C#

Okay, so I thought I would finish this part of the tutorial about reflection, with a quiet and useful example. There is a bit bigger than general examples here on the site, but hopefully you will find it really useful. In this last few parts we have seen that a bunch of stuff uses, so hopefully you can keep it.

When creating any application, there is a general scenario, the desire to save user settings, when you get many settings, you will probably create a setting class, which will have to load the desired settings and handle the savings. Every time you need a new setting in your settings category, you need to update the load () and save () methods to include this new setting. But hey, why do not the settings class find your properties and then load and save them automatically? With reflection, this is quite easy, and if you have read other sections in the reflection section of this tutorial, then you should be able to understand the following example.

To make it better in a small example, I am saving information about one person rather than application settings, but hopefully you will get the general idea anyway. Please keep in mind that the use of reflection will be slow by reading and writing manually known properties, so when you should use it and choose the fast way! Apart from this, in our example, we also use a simple text file to store simple values, only different from one (pipe character). If you are using it for real-world content, then you probably want a better format for your data, maybe xml and of course, there is not much error handling, you should probably add anything As well

Okay, let's start. First of all, our person category, which you can change settings or similar names, to make it more useful to you:


public class Person
{
    private int age = -1;
    private string name = String.Empty;

    public void Load()
    {
        if(File.Exists("settings.dat"))
        {
            Type type = this.GetType();

            string propertyName, value;
            string[] temp;
            char[] splitChars = new char[] { '|' };
            PropertyInfo propertyInfo;

            string[] settings = File.ReadAllLines("settings.dat");
            foreach(string s in settings)
            {
                temp = s.Split(splitChars);
                if(temp.Length == 2)
                {
                    propertyName = temp[0];
                    value = temp[1];
                    propertyInfo = type.GetProperty(propertyName);
                    if(propertyInfo != null)
                        this.SetProperty(propertyInfo, value);
                }
            }
        }
    }

    public void Save()
    {
        Type type = this.GetType();
        PropertyInfo[] properties = type.GetProperties();
        TextWriter tw = new StreamWriter("settings.dat");
        foreach(PropertyInfo propertyInfo in properties)
        {
            tw.WriteLine(propertyInfo.Name + "|" + propertyInfo.GetValue(this, null));
        }
        tw.Close();
    }

    public void SetProperty(PropertyInfo propertyInfo, object value)
    {
        switch(propertyInfo.PropertyType.Name)
        {
            case "Int32":
                propertyInfo.SetValue(this, Convert.ToInt32(value), null);
                break;
            case "String":
                propertyInfo.SetValue(this, value.ToString(), null);
                break;
        }
    }

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

Okay, there are so many things, I know but I will help you in your whole class. First of all, we have private sector, to keep information about our person in the lower part of the class, we have related public assets which use the private sector of the curriculum.

We also have load () method. This file looks for settings.dat, and if it exists, then he reads the entire file and places each row in an array of stars Now, we run through each setting line, and it should be divided into two parts Split: A property name and a well part. If both are present, then we use the type object to get the property with the property name, and then we set the value for it using our setproperty method.

The SetProperty () method changes about the type of property that appears on, and then works accordingly. Right now, it only supports integer and string, but as you may feel it is easy to expand this support.

Save () method An array of assetinfo instances, the individual becomes one for each defined quality of the class, and then uses the text worker to write each property, and its value is in the data file

Now we need some code to use this class. This small application will attempt to load the person with the settings file, and if it does not succeed, then the user will be prompted for the information:


class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();
        person.Load();
        if((person.Age > 0) && (person.Name != String.Empty))
        {
            Console.WriteLine("Hi " + person.Name + " - you are " + person.Age + " years old!");
        }
        else
        {
            Console.WriteLine("I don't seem to know much about you. Please enter the following information:");
            Type type = typeof(Person);
            PropertyInfo[] properties = type.GetProperties();
            foreach(PropertyInfo propertyInfo in properties)
            {
                Console.WriteLine(propertyInfo.Name + ":");
                person.SetProperty(propertyInfo, Console.ReadLine());
            }
            person.Save();
            Console.WriteLine("Thank you! I have saved your information for next time.");
        }
        Console.ReadKey();
    }
}

Everything is very trivial here, except the user, once again, we use the reflection, to get all the public properties of the person class, and then ask for each of them.

As a reader exercise, I suggest that you can increase the individual category to include more information. Just add more assets to it, and you will see that this information has been saved and also loaded.