manav inder
manav inder

Reputation: 3601

Create an Index Based Class in c# .Net

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

Upvotes: 6

Views: 8931

Answers (4)

Tigran
Tigran

Reputation: 62246

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.

Upvotes: 7

user557419
user557419

Reputation:

I'm not sure what you mean here, but I'll say that you have to make ClassObject some sort of IEnumirable type, like List<> or Dictionary<> to use it the way to aim for here.

Upvotes: 0

Joachim VR
Joachim VR

Reputation: 2340

public string this[int index] 
 {
    get 
    { ... }
    set
    { ... }
 }

This will give you an indexed property. You can set any parameter you wish.

Upvotes: 0

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

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.

Upvotes: 9

Related Questions