Search code examples
c#.netoopsetter

Method for changing any field of the class


I have a method Set, and I want to pass name of the field and new value so it could change any field. Like:

Person a = new Person("Marco", 5);
a.Set("age", 6);

My realization doesn't work, how to fix it?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;

namespace Project
{
    public class Person
    {
        string name;
        int age;

        public Person(string name1, int age1)
        {
            name = name1;
            age = age1;
        }
        public void Set(string field_name, string new_value)
        {
            Type obj = typeof(Person);
            obj.GetProperty(field_name).SetValue(null, new_value);
        }
    }
}

Solution

  • Replace null with this to set the value of a property of the current instance of Person:

    obj.GetProperty(field_name).SetValue(this, new_value);
    

    But since you have non-public fields, you should use GetField with some binding flags:

    obj.GetField(field_name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
        .SetValue(this, new_value);
    

    You probably also want a method to get the values and change the type of new_value to object.

    Also note that setting values like this, instead of using strongly typed properties, is both slower and prone to errors. Depending on your requirements, you may want to consider using a Dictionary<TKey, TValue>.