Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass in a property name as a string and assign a value to it?

I'm setting up a simple helper class to hold some data from a file I'm parsing. The names of the properties match the names of values that I expect to find in the file. I'd like to add a method called AddPropertyValue to my class so that I can assign a value to a property without explicitly calling it by name.

The method would look like this:

//C#
public void AddPropertyValue(string propertyName, string propertyValue) {
   //code to assign the property value based on propertyName
}

---

'VB.NET'
Public Sub AddPropertyValue(ByVal propertyName As String, _
                            ByVal propertyValue As String)
    'code to assign the property value based on propertyName '
End Sub

The implementation might look like this:

C#/VB.NET

MyHelperClass.AddPropertyValue("LocationID","5")

Is this possible without having to test for each individual property name against the supplied propertyName?

like image 804
Ben McCormack Avatar asked Aug 09 '10 18:08

Ben McCormack


People also ask

How can I get my name in string?

Usage: // Static Property string name = GetPropertyName(() => SomeClass. SomeProperty); // Instance Property string name = GetPropertyName(() => someObject. SomeProperty);

What is property name in C#?

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.

How do you find a property name?

To get names of properties for a specific type use method Type. GetProperties. Method returns array of PropertyInfo objects and the property names are available through PropertyInfo.Name property.

Why we use get set property in C#?

It is a good practice to use the same name for both the property and the private field, but with an uppercase first letter. The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property.


2 Answers

You can do this with reflection, by calling Type.GetProperty and then PropertyInfo.SetValue. You'll need to do appropriate error handling to check for the property not actually being present though.

Here's a sample:

using System;
using System.Reflection;

public class Test
{
    public string Foo { get; set; }
    public string Bar { get; set; }

    public void AddPropertyValue(string name, string value)
    {
        PropertyInfo property = typeof(Test).GetProperty(name);
        if (property == null)
        {
            throw new ArgumentException("No such property!");
        }
        // More error checking here, around indexer parameters, property type,
        // whether it's read-only etc
        property.SetValue(this, value, null);
    }

    static void Main()
    {
        Test t = new Test();
        t.AddPropertyValue("Foo", "hello");
        t.AddPropertyValue("Bar", "world");

        Console.WriteLine("{0} {1}", t.Foo, t.Bar);
    }
}

If you need to do this a lot, it can become quite a pain in terms of performance. There are tricks around delegates which can make it a lot faster, but it's worth getting it working first.

like image 124
Jon Skeet Avatar answered Nov 15 '22 00:11

Jon Skeet


Using reflection you get the property using the name and set its value... something like:

Type t = this.GetType();
var prop = t.GetProperty(propName);
prop.SetValue(this, value, null);
like image 45
Jaime Avatar answered Nov 14 '22 23:11

Jaime