Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use reflection to get the value of a property by name in a class instance

Lets say I have

class Person
{
    public Person(int age, string name)
    {
        Age = age;
        Name = name; 
    }
    public int Age{get;set}
    public string Name{get;set}
}

and I would like to create a method that accepts a string that contains either "age" or "name" and returns an object with the value of that property.

Like the following pseudo code:

    public object GetVal(string propName)
    {
        return <propName>.value;  
    }

How can I do this using reflection?

I am coding using asp.net 3.5, c# 3.5

like image 448
TheMoot Avatar asked Jun 21 '11 19:06

TheMoot


People also ask

How do you find the reflection of a property name?

Get Property Names using Reflection [C#] Method returns array of PropertyInfo objects and the property names are available through PropertyInfo.Name property. If you want to get only subset of all properties (e.g. only public static ones) use BindingFlags when calling GetProperties method.

What is the use of reflection in C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

Does GetCustomAttribute use reflection?

Assembly; Console. WriteLine(bookAssembly); The code from earlier that uses Attribute. GetCustomAttribute() is also an example of Reflection.

What is GetProperty C#?

GetProperty(String, BindingFlags) Searches for the specified property, using the specified binding constraints. public: virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, System::Reflection::BindingFlags bindingAttr); C# Copy.


1 Answers

I think this is the proper syntax...

var myPropInfo = myType.GetProperty("MyProperty");
var myValue = myPropInfo.GetValue(myInstance, null);
like image 162
Todd Avatar answered Sep 23 '22 01:09

Todd