How to set Vaues to the Nested Property using Reflection

Joined
Oct 31, 2021
Messages
13
Programming Experience
Beginner
how can i dynamically set values to the name of country district city landmark
C#:
public class Region
{
    public int id;
    public string name;
    public Country CountryInfo{get;set;} = new Country();
    public City CityInfo{get; set;}= new City(); 
  public District DistrictInfo{get; set;}= new District();
    public  Landmark LandmarkInfo{get; set; }= new Landmark();
}

public class Country
{
    public int id;
    public string name;
}

public class City
{
    public int id;
    public string name;
}

public class District
{
    public int id;
    public string name;
}
public class Landmark
{
    public int id;
    public string name;
}
 
Last edited by a moderator:
Get the FieldInfo from type Country and use SetValue on an instance.
C#:
var r = new Region();
var field = typeof(Country).GetField("name"); //or r.CountryInfo.GetType().GetField
field.SetValue(r.CountryInfo, "new name");
 
Perhaps I'm missing something. All the fields look to be public. Why even use reflection?
 
Back
Top Bottom