Is there something like Python's getattr() in C#? - TagMerge
3Is there something like Python's getattr() in C#?Is there something like Python's getattr() in C#?

Is there something like Python's getattr() in C#?

Asked 1 years ago
13
3 answers

There is also Type.InvokeMember.

public static class ReflectionExt
{
    public static object GetAttr(this object obj, string name)
    {
        Type type = obj.GetType();
        BindingFlags flags = BindingFlags.Instance | 
                                 BindingFlags.Public | 
                                 BindingFlags.GetProperty;

        return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null);
    }
}

Which could be used like:

object value = ReflectionExt.GetAttr(obj, "PropertyName");

or (as an extension method):

object value = obj.GetAttr("PropertyName");

Source: link

5

Use reflection for this.

Type.GetProperty() and Type.GetProperties() each return PropertyInfo instances, which can be used to read a property value on an object.

var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null)

Type.GetMethod() and Type.GetMethods() each return MethodInfo instances, which can be used to execute a method on an object.

var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null);

If you don't necessarily know the type (which would be a little wierd if you new the property name), than you could do something like this as well.

var result = dt.GetType().GetProperty("Year").Invoke(dt, null);

Source: link

1

Yes, you can do this...

typeof(YourObjectType).GetProperty("PropertyName").GetValue(instanceObjectToGetPropFrom, null);

Source: link

Recent Questions on c#

    Programming Languages