demo stack February 2016

Dynamically returning property values

I have a class like:

Class A
{
        public double? LondonTime { get; set; }
        public double? DelhiTime { get; set; }
}

Now, in my another class, I want to make these properties dynamic. Class B has a function foo(ClassA):

Class B

private void foo(Class A)
double d;
{
 If(some condition for London Time)
  {
    //How to pass LondonTime Property
    d = returnTime(); 
   }
 else if(some condition for Delhi Time)
 {
   //How to pass DelhiTimeProperty
    d = returnTime();
 }
}

private double returnTime(????) //What should I Pass here as an argument
{
  if(LondonTimeProperty Passed)
  {
    Some logic
  }
  if(DelhiTimeProperty Passed)
  {
    Some logic
  }  
  return 0;
}

Here, this is just an example, if it was just giving me 1 dynamic value, I can adjust it.

So, is there a way that I pass an argument in returnTime based on some condition and know what to return ?

Answers


nAviD February 2016

Use this :

 public static dynamic GetPropertyValue(object obj, string propName)
        {
            return obj.GetType().GetProperty(propName).GetValue(obj, null);
        }

and then you can use:

GetPropertyValue(new ClassA(),"LondonTime");


Kyle W February 2016

Some general questions and comments:

Why are you using a double instead of a DateTime?

What do you mean by dynamic?

It seems like all you need is this:

double? GetLondonTime(A a)
{
    //Some logic
}

double? GetDelhiTime(A a)
{
    //Some logic
}

void foo(A a)
{
    If(some condition for Delhi)
        return GetDelhiTime(a);
    If(some condition for London)
        return GetLondonTime(a);
    return 0;
}

If you were using a DateTime, you could probably determine if it was Delhi or London time based on the TimeZone.


LessNoviceProgrammer February 2016

I'm not sure if this is what you're looking for, but I don't really see a reason to complicate it by doing reflection or dynamic objects, unless there is a lot more going on:

    public class Times {
    public enum : int City {
        LONDON,
        NEW_DEHLI,
        OTHER_PLACE
    };
    public /*DateTime*/double GetTime(City) {
        switch(City) {
            case City.NEW_DEHLI:
            return getDehliTime();
        case City.London:
            return getLondonTime();
        default:
            return DateTime.Now;
        }
    } 
}

Post Status

Asked in February 2016
Viewed 3,100 times
Voted 8
Answered 3 times

Search




Leave an answer