Suppose there is a class

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

What you need to do to be able to initialize the field instance of the class through the instance["Age"] = 5; And is it possible?

  • 3
    why not public int Age {get;set;} ? and let me correct you not the properties but the fields - Bald Nov.
  • @ Bald56rus What's the difference between a field and a simple (especially automatic) property? :) Do not just talk about encapsulation. - andreycha
  • @andreycha I do not know the answer :) I use the properties like something on the machine, because the examples I’ve seen are used everywhere, properties I know the advantages of this answer - Bald
  • one
    @ Bald56rus in the same answer says that there is no difference. It appears only when it is necessary to screw some logic over the field. And here properties really come to the rescue (as a slightly more convenient replacement for a pair of methods GetXXX / SetXXX). So if you have a simple POCO, there are more than enough fields. - andreycha
  • one
    @andreycha and why then do not use automatic properties except for explicit cases when fields are necessary? even in Roso ?! - Bald

3 answers 3

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 a good way, you need to add a validation (for example, that the name of an existing field is specified, or that the type of the value being set corresponds to the field type) and caching the list of fields (to request them only once).


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

    initialize the field class instance through instance ["Age"] = 5; And is it possible?

    You can simply write instance.Age = 5; .
    To do this, use dynamic and ExpandoObject . An example is here .

      reimplement the operator [] something like this:

       class a { public int age; public string name; public object this[int i] { get { return age[i]; } set { age[i] = value; } } } 
      • and how do u represent age[i] ? - Grundy