0

I'm trying to access member values of the following class:

public class EditorialDateFormat
{
       public string en; <------ TRYING TO GET ITS VALUE
       public string fr; <------ OR THIS VALUE
       public string Default;<-- OR THIS ONE
 }
public class Params
{
      public string Template;
      public string MainTagID;
      public string[] NavigationFilters;
      public EditorialDateFormat EditorialDateFormat;
}
public class Site
{
      public string Name;
      public string CreationFolder;
      public Params Params;
      public string[] Feed;
      public string Endpoint;
      public string[] TargetDatabases;
}

I could do it easily like : site.Params.EditorialDateFormat.en(for example) but "en" string is actually saved in a variable.

I tried the following code :

// Myvariable contains "en"
object c = GetPropValue(site.Params.EditorialDateFormat, MyVariable); 

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetMember(propName);
}

But it returns me a MemberInfo object without the member value I would appreciate some help! Thanks in advance

3
  • You´re almost there: you have to get the value for the obtained MemberInfo on the given instance of your class, something like : GetMember(propName).GetValue(src, null). Commented Sep 14, 2018 at 13:26
  • Not sure but you want en value if null then fr and if that's also null then you want default value right? Commented Sep 14, 2018 at 13:28
  • Uttam Ughareja : yes that's my expected behaviour ! Commented Sep 14, 2018 at 13:29

2 Answers 2

4

You want to read field (public instance field's value), that's why we put GetField:

//TODO: rename the method: it doesn't read property (Prop) 
public static object GetPropValue(object src, string propName) {
  return src
    .GetType()
    .GetField(propName, BindingFlags.Public | BindingFlags.Instance)
    .GetValue(src);
}
Sign up to request clarification or add additional context in comments.

Comments

1
public class EditorialDateFormat
{
    private string _en;

    public string en
    {
        get { return !string.IsNullOrEmpty(_en) ? _en : fr; }
        set { _en = value; }
    }
    private string _fr;

    public string fr
    {
        get { return !string.IsNullOrEmpty(_fr) ? fr : Default; }
        set { _en = value; }
    }

    public string Default { get; set; }
}

and you can use it like var c=site.Params.EditorialDateFormat.en in elegant way

1 Comment

Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.