Search code examples
c#generic-programming

Generic classes and its child


I have base class Entity and an enheritance class say Home ,

public class Home : Entity
{
    public int CityId{get;set;}
}

public class Town : Entity 
{
    public int  CityId {get;set}
    public Home CityHall {get;set;}
    public List<Home > Homes{get;set;}
}

I want to set the CityId for Town and its children so a first try I did the following

public class DataAccessBase<T> where T : Entity
{
    public int Add(T entity)
    {
        Type t = typeof(T);
        PropertyInfo prop = t.GetProperty("CityId");
        if (prop != null)
        {
            prop.SetValue(entity, 2);
        }
    }
}

this work only for the parent how to access children , I want to d othat generically simply because I have a dataaaccesslayer that insert of Database genrically


Solution

  • It looks like there are two unrelated problems

    • how to set property of an object without knowledge if property is there: reflection as you have it solve that. Note that this is not very C# way - you'd use some interface and restrict generics to that interface to allow strongly typed access to properties.

    • how to enumerate "child" objects without knowing type: traditional solution again is to add interface for "GetChildren" functionality. Alternatively you can go with reflection and find all properties that are of "child" type and combine with all properties that are of type IEnumerable<"child type">.

      If you can use some convention dynamic could be easier alternative to reflection (i.e. every type exposes Children property to enumerate them:

      dynamic town = GetTown();
      foreach(dynamic child in town.Children) {...}