I have the following class:
public class Employees {
public string field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
public string field4 { get; set; }
}
And i want to change values to all those members.
so i can to something like that:
Employees.field1 = "ghgf";
Employees.field2 = "ghgf";
Employees.field3 = "ghgf";
Employees.field4 = "ghgf";
but it's very ugly. and the amount of members will be 30, so this is not a good way...
I want to use for loop, that run over all the members and dynamic took the relevant field and change the value. for example:
for(int i=1; i<4; i++) {
var field = "field" + i;
Employees.field(the Var!!) = "fgdfd";
}
but in this line:
Employees.field(the Var!!) = "fgdfd";
I have a problem because field is the var that was defined in the for loop.
You can do it the hard (and not correct, IMO) way, using reflection.
But if you have 30 variable like this, change your approach: use a List<string>
, or a Dictionary <whateverKey, string>
to store all your fields
If you really must do it using reflection, you can do it like so:
var employees = new Employees();
var type = employees.GetType();
for (int i = 1; i <= 4; ++i)
type.GetProperty("field"+i).SetValue(employees, "abcde");
Console.WriteLine(employees.field1); // Prints "abcde"
As other folks have pointed out, using reflection in this way seems a little suspect. It looks like you should be doing it a different way, for example by using a Dictionary<string,string>
.
You can try using Reflection
Type type = typeof(Employees);
PropertyInfo pi = this.GetType().GetProperty();
pi.SetField(this, value);
Here is the MSDN link : https://msdn.microsoft.com/en-us/library/ms173183.aspx
Try this approach (using GetMembers()) to get all the members of a class and loop them.
Employees myEmployees = new Employees();
MemberInfo[] members = myType.GetMembers();
for (int i =0 ; i < members.Length ; i++)
{
// Display name and type of the concerned member.
Console.WriteLine( "'{0}' is a {1}", members[i].Name, members[i].MemberType);
}
You can do it using reflexion like that:
var myEmployees = new Employees();
var properties = myEmployees.GetType().GetProperties();
foreach (var field in properties)
{
field.SetValue(myEmployees, "NewValue");
}
// Print all field's values
foreach (var item in properties)
{
Console.WriteLine(item.GetValue(myEmployees));
}
Otherwise you can use a list or a dictionary or create a new struct that offre you more flexibility and let you able to control more properties of the field:
struct FieldProperties
{
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
...
}
List<FieldProperties> lst = new List<FieldProperties>();