'Reflection to hierarchy of type
Let's consider following example.
public class User
{
public string Name { get; set; }
public Department Department { get; set; }
}
public class Department
{
public string Name { get; set; }
public Company Company { get; set; }
}
public class Company
{
public string Name { get; set; }
}
Above Usage is like.
User user = new User();
user.Department = new Department();
user.Department.Company = new Company();
There is one function.
public static void Print(Company company)
{
// Want to get information from companyType about it's declaring or parent type.
// Like Company -> Department -> User
Console.WriteLine(company.Name);
}
Now if I pass company that belong nested to the User Type, I need hierarchy from that like
Company -> Department -> User
It is possible that Company may present at other level in some other type so at that time that heirarchy needs to display. For example if It is present Order -> OrderDetail -> Product -> Company at that time different hierarchy needs to display.
Note: If I have entire type present then it is easy to get down but I want to go upward upto the type.
Solution 1:[1]
public class Program
{
public static void Main()
{
User user = new User();
user.Name = "Tom Hanks";
user.Department = new Department();
user.Department.Company = new Company(user);
user.Department.Company.Name = "Company GMH";
Print(user.Department.Company);
}
public static void Print(Company company)
{
Console.WriteLine(company.User.Name);
}
}
public class User
{
public string Name { get; set; }
public Department Department { get; set; }
}
public class Department
{
public string Name { get; set; }
public Company Company { get; set; }
}
public class Company
{
public string Name { get; set; }
public User User { get; set; }
public Company(User user)
{
this.User = user;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Adam Wróbel |
