Friday, November 7, 2014

Accessing Class Properties by Indexer

Below sample code in C# explains how we can access any class properties by indexer also by modifying that class as below to make it support that functionality.

public class Sample
{
    Dictionary<string,dynamic> dic;
    int _id;
    public int Id{
        get{ return _id; }
        set{ _id=value; dic["Id"]=value; }
    }
    string _name;
    public string Name{
        get{ return _name; }
        set{ _name=value; dic["Name"]=value; }
    }
    bool _adult;
    public bool IsAdult{
        get{ return _adult; }
        set{ _adult=value; dic["IsAdult"]=value; }
    }
  
    public Sample(){
        dic = new Dictionary<string,dynamic>();
        //Add properties with their default value
        foreach(var item in this.GetType().GetProperties()){
            try{ dic.Add(item.Name,item.GetValue(this)); }catch{ /*ignore Indexer property*/ }
        }
    }
    public dynamic this[string propName]{
        get{
            if(dic.ContainsKey(propName))
                return dic[propName];
            else return null;  
        }
        set{
            var prop = this.GetType().GetProperty(propName);
            if(prop != null)
            {
                prop.SetValue(this, value);
            }
        }
    }
}

And below is the code for updating and accessing the properties by Indexer.

//Accessing Object Properties by Indexer
    Sample obj = new Sample();
  
    Console.WriteLine(obj["Id"]);
  
    obj.Id = 1;
    Console.WriteLine(obj["Id"]);
  
    obj["Id"] = 3;
    Console.WriteLine(obj["Id"]);
  
    obj["Name"] = "Alice";
    Console.WriteLine(obj["Name"]);
    Console.WriteLine(obj.Name);
  
    obj["IsAdult"] = true;
    Console.WriteLine(obj["IsAdult"]);

If you have any suggestions or comments, share it in Comments section.

Download above code as Linqpad code file:
SampleCode.linq

No comments:

Post a Comment