-2

I have a helper manager with following properties:

public class ClientDetails
{
    public string ContactName { get; set; }
    public string ContactTelephone { get; set; }
    public string Add1 { get; set; }
    public string Add2 { get; set; }
    public string Town { get; set; }
    public string PostCode { get; set; }
}

I want to 'get' all these properties in one method. Something like:

protected string ContactDetails(string propertyName)
{
    var _clientDetails = ManagerHelper.ClientDetails();
    var temp = typeof (ClientDetails);

    var value = temp.GetProperty(propertyName);

    return value.GetValue(_clientDetails); //ERROR
}

I have read somewhere that you can use reflection to do these kind of things but I'm not familiar with reflection. I have tried using reflection above however it gives me an error on _clientDetails.

So if I call this method like string address1 = ContactDetails("Add1") then it returns me the value in ClientDetails().Add1.

Error is "No overload for method 'GetValue takes 1 arguments".

Yagzii
  • 286
  • 3
  • 14
  • 1
    What is the error? Saying, "It gave me an error" is about as helpful as saying, "It don't worky" – Craig W. Dec 04 '14 at 16:12
  • http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp – vidriduch Dec 04 '14 at 16:13
  • Are you sure `ManagerHealper.ClientDetails()` is giving back a valid `ClientDetails` object? (check the spelling, BTW) – D Stanley Dec 04 '14 at 16:15
  • Yes, it giving me a valid object. Need to changing the spelling:) – Yagzii Dec 04 '14 at 16:19
  • I have looked at http://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp but it's return an object. How do I retrieve the value in the object in run time? – Yagzii Dec 04 '14 at 16:23
  • Just look at the documentation for the method you're trying to call. – Servy Dec 04 '14 at 16:23
  • The error is telling you - you can't call `GetValue` with one parameter (until .net 4.5 at least). [Read the docs](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getvalue(v=vs.100).aspx) – James Thorpe Dec 04 '14 at 16:24
  • I have tried return `value.GetValue(_clientDetails , null);` which returns an object but I don't know how could i get the string I want from it – Yagzii Dec 04 '14 at 16:26
  • @yagzii did you tryed the code in my answer? `return (string)value.GetValue(_clientDetails, null);` – Ludovic Feltz Dec 04 '14 at 16:30

1 Answers1

0

Try this:

return (string)value.GetValue(_clientDetails, null);
Ludovic Feltz
  • 11,416
  • 4
  • 47
  • 63
  • @DStanley No it is not optionnal see: http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getvalue(v=vs.100).aspx – Ludovic Feltz Dec 04 '14 at 16:27