c# – Referring to Class Fields by Name

Question:

Let's say there is a class

class A 
{
    public int Age;
    public string Name;
}

What needs to be done so that you can initialize the fields of the class instance["Age"] = 5; through instance["Age"] = 5; And is it possible?

Answer:

This can be done using an indexer ( [] ) and reflection. Sample code:

public object this[string fieldName]
{
    get
    {
        var field = this.GetType().GetField(fieldName);
        return field.GetValue(this);
    }
    set
    {
        var field = this.GetType().GetField(fieldName);
        field.SetValue(this, value);
    }
}

This code works for all instance fields. If you need to install incl. and static fields – you need to change the code. Also, in an amicable way, you need to add validation (for example, that the name of an existing field is specified, or that the type of the value to be set corresponds to the type of the field) and caching of the list of fields (so that they are requested only once).


Although it's best to use the fields or properties themselves. Or replace your class with a dictionary, where the key will be the name of the field / property.

Scroll to Top