6

Consider these properties,

        double _temperature;
        public double Temperature
        {
            get { return _temperature; }
            set { _temperature = value; }
        }
        double _humidity;
        public double Humidity
        {
            get { return _humidity; }
            set { _humidity = value; }
        }
        bool _isRaining;
        public bool IsRaining
        {
            get { return _isRaining; }
            set { _isRaining = value; }
        }

And now I want to make a list/collection/container of properties like this,

PropertyContainer.Add(Temperature);  //Line1
PropertyContainer.Add(Humidity);     //Line2
PropertyContainer.Add(IsRaining);    //Line3

I want to make this such that later on I may be able to access the current values of properties using index, something like this,

object currentTemperature =  PropertyContainer[0];
object currentHumidity    =  PropertyContainer[1];
object currentIsRaining   =  PropertyContainer[2];

But obviously, this is not going to work, since PropertyContainer[0] will return the old value - the value which Temperature had at the time of adding Temperature to the container (see the Line1 above).

Is there any solution to this problem? Basically I want to access current values of properties uniformly; the only thing that can change is, the index. The index however could be string as well.

PS: I don't want to use Reflection!

Nawaz
  • 353,942
  • 115
  • 666
  • 851

1 Answers1

11

Well, you could use Lambdas:

List<Func<object>> PropertyAccessors = new List<Func<object>>();
PropertyAccessors.Add(() => this.Temperature);
PropertyAccessors.Add(() => this.Humidity);
PropertyAccessors.Add(() => this.IsRaining);

then you could to this:

object currentTemperature = PropertyAccessors[0]();
Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • this is awesome solution. after I posted the question, I got the same solution from [another topic](http://stackoverflow.com/questions/1402803/c-passing-properties-by-reference). thanks a lot for the quick response with this awesome trick! – Nawaz Dec 20 '10 at 09:19
  • 1
    Oops, I forgot that. Actually before it was asking me to wait 5 minutes, God knows why. Anyway, answer accepted and +1 from me. – Nawaz Dec 20 '10 at 11:34