-1

I have to set the value of a property custom class with reflection. This is an example of what I have to get.

class Phone
{
    public detailsTelephone DetailsTelephone { get; set; } = new detailsTelephone();
}

class detailsTelephone
{
    public PhoneName PHONENAME { get; set; } = new PhoneName();
    public PhoneCover PHONECOVER { get; set; } = new PhoneCover();
}

class PhoneName
{
    public string LenghtName { get; set; } = string.Empty;
}

class PhoneCover
{
    public string ColorCover { get; set; } = string.Empty;
}

class Program
{
    static List<Phone> PhoneList = new List<Phone>();

    static void Main(string[] args)
    {
        PhoneList.Add(new Phone());

        detailsTelephone p = PhoneList.Last().DetailsTelephone;
        var property = typeof(detailsTelephone).GetProperty("PHONENAME");
        property.SetValue(p.PHONENAME.LenghtName, "1000", null);

        Console.WriteLine(PhoneList.Last().DetailsTelephone.PHONENAME.LenghtName);
        Console.ReadLine();
    }
}

I updated the post with the real structure I have in the project. The problem is that I have to find the first property by name (PHONENAME) and then set the PHONENAME.LenghtName to 1000 property.

Thanks in advance.

Frazzio
  • 17
  • 6
  • I have updated the post but I don't know if it can be the right way – Frazzio Jun 23 '19 at 12:28
  • You want to set the last phone's `PhoneName` to `Samsung`? I don't really understand what you actually want here – Ammar Jun 23 '19 at 12:40
  • I updated the post again. After selecting the property with the query how can I set the property value? – Frazzio Jun 23 '19 at 12:43
  • You can simply do `PhoneList.Last().DetailsTelephone.PhoneName = "Samsung"`, no need to use linq to select properties here. But make sure that `PhoneList` should has elements, and `DetailsTelephone` of last phone is not `null` to avoid `NullReferenceException` – Ammar Jun 23 '19 at 12:45
  • In this small example you are actually right, but in my project I need to first select the property based on the name and then set its value. – Frazzio Jun 23 '19 at 12:50
  • [Can I set a property value with Reflection?](https://stackoverflow.com/questions/7718792/can-i-set-a-property-value-with-reflection) – Ammar Jun 23 '19 at 12:52
  • I updated the post with the example Ammar's suggestion but now returns the following error: (in property.SetValue (p, "Samsung", null);) error: Destination requested by non-static method. – Frazzio Jun 23 '19 at 13:09

1 Answers1

0

The problem lies (based on updated OP) in your Phone class. You haven't initialized your DetailsTelephone property. The following should help you fix the error.

class Phone
{
    public detailsTelephone DetailsTelephone { get; set; } = new detailsTelephone();
}
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51