I'm working in C#, using Linq Dynamic to do some sorting, so I needed to get property names like string
.
When the properties are simple, they do not cause me any conflict, since I can use nameof()
perfectly.
My problem is getting the names of child properties of objects.
I give an example for you to interpret.
public class Padre
{
public string Prop1 { get; set; }
public Hijo H { get; set; }
}
public class Hijo
{
public string Prop2 { get; set; }
}
When I want to access the name of Prop1
, I can do it perfectly as nameof(Prop1)
.
The problem occurs when wanting to obtain the name of Prop2
within an instance of Padre
, for example
Padre p = new Padre();
string nombreProp2 = nameof(p.H.Prop2);
Where I intend to get the string "H.Prop2"
but get only Prop2
, currently I get the value manually by doing something like
string nombreProp2 = string.Format("{0}.{1}",nameof(p.H),nameof(p.H.Prop2))
Is there a more direct method of obtaining this data?
I hope it helps you:
And you use it:
And the result would be "H.Prop2".