Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an Index Based Class in c# .Net

Tags:

c#

.net

oop

i've some classes and want to access their properties using index or something like

ClassObject[0] or better will be ClassObject["PropName"]

instead of this

ClassObj.PropName.

Thanks

like image 540
manav inder Avatar asked Aug 17 '11 09:08

manav inder


2 Answers

You need indexers:

http://msdn.microsoft.com/en-us/library/aa288465(v=vs.71).aspx

public class MyClass
{
    private Dictionary<string, object> _innerDictionary = new Dictionary<string, object>();

    public object this[string key]
    {
        get { return _innerDictionary[key]; }
        set { _innerDictionary[key] = value; }
    }
}

// Usage
MyClass c = new MyClass();
c["Something"] = new object();

This is notepad coding, so take it with a pinch of salt, however the indexer syntax is correct.

If you want to use this so you can dynamically access properties, then your indexer could use Reflection to take the key name as a property name.

Alternatively, look into dynamic objects, specifically the ExpandoObject, which can be cast to an IDictionary in order to access members based on literal string names.

like image 132
Adam Houldsworth Avatar answered Oct 20 '22 03:10

Adam Houldsworth


You can do something like this, a pseudocode:

    public class MyClass
    {

        public object this[string PropertyName]
        {
            get
            {
                Type myType = typeof(MyClass);
                System.Reflection.PropertyInfo pi = myType.GetProperty(PropertyName);
                return pi.GetValue(this, null); //not indexed property!
            }
            set
            {
                Type myType = typeof(MyClass);
                System.Reflection.PropertyInfo pi = myType.GetProperty(PropertyName);
                pi.SetValue(this, value, null); //not indexed property!
            }
        }
    }

and after use it like

MyClass cl = new MyClass();
cl["MyClassProperty"] = "cool";

Note that this is not complete solution, as you need to "play" with BindingFlags during reflection access if you want to have non public properties/fields, static ones and so on.

like image 37
Tigran Avatar answered Oct 20 '22 04:10

Tigran