C# setting value to the fields, properties, etc.
It is possible to get methods, fields, properties, enums, interfaces etc. from Class.GetType(). It is also possible to change them dynamically (on runtime).
for example, when we have fields of type String
and we want to set their value equal to their names:
class Base {
public string myField;
public string myProperty {get; set;}
}
class Derived: Base {
public Derived {
var fields = base.GetType().GetFields();
foreach (var field in fields) {
field.SetValue(this, field.Name);
}
}
}
Get an array of fields with type of String
:
class MyClass {
public string x = "x", apple = "Apple", name = "C#";
public string[] GetArray()
{
var fields = GetType().GetFields();
var arr = new List<string>(fields.Length);
foreach (var field in fields)
arr.Add((string)field.GetValue(this));
return arr.ToArray();
}
}