Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Accessing object properties indexer style

Tags:

c#

Is there any tool,library that would allow me to access my objects properties indexer style ?

public class User
{
    public string Name {get;set;}
}

User user = new User();
user.Name = "John";

string name = user["Name"];

Maybe the dynamic key word could help me here ?

like image 457
user256034 Avatar asked May 12 '11 08:05

user256034


5 Answers

You can use reflection to get property value by its name

   PropertyInfo info = user.GetType().GetProperty("Name");
   string name = (string)info.GetValue(user, null);

And if you want to use index for this you can try something like that

    public object this[string key]
    {
        get
        {
             PropertyInfo info = this.GetType().GetProperty(key);
             if(info == null)
                return null
             return info.GetValue(this, null);
        }
        set
        {
             PropertyInfo info = this.GetType().GetProperty(key);
             if(info != null)
                info.SetValue(this,value,null);
        }
    }
like image 180
Stecya Avatar answered Oct 05 '22 22:10

Stecya


Check out this about indexers. The dictionary stores all the values and keys instead of using properties. This way you can add new properties at runtime without losing performance

public class User
{
    Dictionary<string, string> Values = new Dictionary<string, string>();
    public string this[string key]
        {
            get
            {
                return Values[key];
            }
            set
            {
                Values[key] = value;
            }
        }
}
like image 24
Oskar Kjellin Avatar answered Oct 05 '22 23:10

Oskar Kjellin


You could certainly inherit DynamicObject and do it that way.

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetindex.aspx

Using the simple indexer method mentioned here by others would limit you to either returning only 'object' (and having to cast) or having only string types in your class.

Edit: As mentioned elsewhere, even with dynamic, you still need to use either reflection or some form of lookup to retrieve the value inside the TryGetIndex function.

like image 29
Andrew Hanlon Avatar answered Oct 05 '22 21:10

Andrew Hanlon


You cannot do this until the class implements a Indexer.

like image 29
Ankur Avatar answered Oct 05 '22 21:10

Ankur


If you just want to access a property based on a string value you could use reflection to do something similar:

string name = typeof(User).GetProperty("Name").GetValue(user,null).ToString();
like image 43
Ben Robinson Avatar answered Oct 05 '22 21:10

Ben Robinson