views:

35

answers:

2

In actionscript an object's property can be accesses in this way:

object["propertyname"]

Is something like this possible in c#, without using reflection?

+2  A: 

No, you have to use reflection.
If could at most create an helper extension method like in this example:

using System;

static class Utils {
    public static T GetProperty<T>(this object obj, string name) {
        var property = obj.GetType().GetProperty(name);
        if (null == property || !property.CanRead) {
            throw new ArgumentException("Invalid property name");
        }
        return (T)property.GetGetMethod().Invoke(obj, new object[] { });
    }
}

class X {
    public string A { get; set; }
    public int B { get; set; }
}

class Program {
    static void Main(string[] args) {
        X x = new X() { A = "test", B = 3 };
        string a = x.GetProperty<string>("A");
        int b = x.GetProperty<int>("B");
    }
}

This is not good, however.
First because you are turning compile-time errors in runtime errors.
Second, the performance hit from reflection is unjustified in this case. I think that the best advice here is that you should not try to program in C# as if it was ActionScript.

Paolo Tedesco
Thx for the reply.I was just wondering if avoiding reflection was an option, because of the performance issues.In this case, the code would be used in a recursive method of a composite object structure, that is used quite a lot.Is reflection the way to go here?
Bert Vandamme
@Bert Vandamme: I would tell to use reflection only when you don't know the object tpye a priori, but could you make an example?
Paolo Tedesco
I assume, at a point where you know the property type, you should also know the owner's type well enough to avoid reflection, even if abstracted to just an interface defining that single property. :)I agree, reflection should be used only if you just don't know anything at all at compile time.
back2dos
A: 

You can define indexer in your class:

public class IndexerTest
{
    private Dicionary<string, string> keyValues = new ...

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

And use it like this:

string property = indexerTest["propertyName"];
Andrew Bezzub
the bracket-syntax is a little missleading. in ECMA-script object[expression] is equivalent to object.ident, if the string representation of expression is "ident". What Bert seems to be looking for is an equally short way to perform dynamic property access in C#.
back2dos