Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List/Collection of references to Properties

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!

like image 674
Nawaz Avatar asked Dec 20 '10 08:12

Nawaz


1 Answers

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]();
like image 196
Botz3000 Avatar answered Nov 01 '22 02:11

Botz3000