Setting/getting the class properties by string name

C#ReflectionProperties

C# Problem Overview


What I'm trying to do is setting the value of the property in a class using a string. For example, my class has the following properties:

myClass.Name
myClass.Address
myClass.PhoneNumber
myClass.FaxNumber

All the fields are of string type so I know ahead of time that it's always a string. Now, I want to be able to set the properties using a string as you could do with a DataSet object. Something like this:

myClass["Name"] = "John"
myClass["Address"] = "1112 River St., Boulder, CO"

Ideally, I want to just assign a variable and then set the property using that string name from the variable:

string propName = "Name"
myClass[propName] = "John"

I was reading about reflection and maybe it's the way to do it but I'm not sure how to go about setting that up while keeping the property access intact in the class. I want to still be able to use:

myClass.Name = "John"

Any code examples would be really great.

C# Solutions


Solution 1 - C#

You can add indexer property, a pseudocode:

public class MyClass 
{
     public object this[string propertyName] 
     {
        get
        {
           // probably faster without reflection:
           // like:  return Properties.Settings.Default.PropertyValues[propertyName] 
           // instead of the following
           Type myType = typeof(MyClass);                   
           PropertyInfo myPropInfo = myType.GetProperty(propertyName);
           return myPropInfo.GetValue(this, null);
        }
        set
        {
           Type myType = typeof(MyClass);                   
           PropertyInfo myPropInfo = myType.GetProperty(propertyName);
           myPropInfo.SetValue(this, value, null);
        }
     }
}

Solution 2 - C#

You can add an indexer to your class and use reflection to aces the properties:

using System.Reflection;

public class MyClass {

    public object this[string name]
    {
        get
        {
            var properties = typeof(MyClass)
                    .GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var property in properties)
            {
                if (property.Name == name && property.CanRead)
                    return property.GetValue(this, null);
            }

            throw new ArgumentException("Can't find property");

        }
        set {
            return;
        }
    }
}

Solution 3 - C#

May be something like this?

    public class PropertyExample
{
	private readonly Dictionary<string, string> _properties;
	
	public string FirstName
	{
		get { return _properties["FirstName"]; }
		set { _properties["FirstName"] = value; }
	}

	public string LastName
	{
		get { return _properties["LastName"]; }
		set { _properties["LastName"] = value; }
	}
	public string this[string propertyName]
	{
		get { return _properties[propertyName]; }
		set { _properties[propertyName] = value; }
	}

	public PropertyExample()
	{
		_properties = new Dictionary<string, string>();
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPatratacusView Question on Stackoverflow
Solution 1 - C#TigranView Answer on Stackoverflow
Solution 2 - C#Dennis TraubView Answer on Stackoverflow
Solution 3 - C#DeitroView Answer on Stackoverflow