How can I get the full name of a nested property by its parent using reflection in C#? I mean, for example we have this classes:
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public DateTime? DateOfBirth { get; set; }
public Grade Grade { get; set; }
}
public class Grade
{
public int GradeId { get; set; }
public string GradeName { get; set; }
public string Section { get; set; }
public GradGroup GradGroup { get; set; }
}
public class GradGroup
{
public int Id { get; set; }
public string GroupName { get; set; }
}
I have "GradGroup" and Student as method parameters and want "Grade.GradeGroup" as output:
public string GetFullPropertyName(Type baseType, string propertyName)
{
// how to implement that??
}
Call the method:
GetFullPropertyName(typeof(Student), "GradeGroup"); // Output is Grade.GradeGroup
The property may not be unique as it might exist on several components so you should return an IEnumerable<string>
. That being said you can traverse the property tree using GetProperties
of Type
:
public static IEnumerable<string> GetFullPropertyName(Type baseType, string propertyName)
{
var prop = baseType.GetProperty(propertyName);
if(prop != null)
{
return new[] { prop.Name };
}
else if(baseType.IsClass && baseType != typeof(string)) // Do not go into primitives (condition could be refined, this excludes all structs and strings)
{
return baseType
.GetProperties()
.SelectMany(p => GetFullPropertyName(p.PropertyType, propertyName), (p, v) => p.Name + "." + v);
}
return Enumerable.Empty<string>();
}
Here are some useful references
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With