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]{
                return dic[propName];
            else return null;  
            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();
    obj.Id = 1;
    obj["Id"] = 3;
    obj["Name"] = "Alice";
    obj["IsAdult"] = true;

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

Download above code as Linqpad code file:

No comments:

Post a Comment