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:

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,415
Location
Norway
Programming Experience
10+
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");
 

Skydiver

Staff member
Joined
Apr 6, 2019
Messages
5,085
Location
Chesapeake, VA
Programming Experience
10+
Perhaps I'm missing something. All the fields look to be public. Why even use reflection?
 
Top Bottom