How to Reference Class Properties with Strings Using ASP.NET Reflection

I often want to get (and less frequently set) the value of a class property using a string containing the property name rather than a standard dot reference. 

So instead of this: 

// the normal way 
string Name = customer.Name

I want to be able to do this: 

// makes the class property look like a dictionary item
string Name = customer["Name"];

Or 

string ColumnName = "Name";
string Name = customer[ColumnName];

(Javascript aficionados will recognize this dual personality immediately, as it’s a natural behavior for javascript objects.)

You can add this dictionary-like capability to any class by adding the following indexer property. No changes are needed.

If you prefer, you can create a small class containing only the indexer property and then have other classes inherit it. That’s what I do in the example at https://dotnetfiddle.net/2klk3x. (See the IndexerProperty class.)

public object this[string propertyName]
{
    get { return this.GetType().GetProperty(propertyName).GetValue(this); }
    set { this.GetType().GetProperty(propertyName).SetValue(this, value); }
}

The dictionary syntax is especially helpful when using LINQ. Below is a small function that takes a list of customers and sorts it by SortColumn, a string holding the name of the column.

private List<Customer> SortCustomers(<List<Customer> customers, string SortColumn)
{
   return customers.OrderBy(cust =>cust[SortColumn]).ToList();
}

WARNING: As usual when using reflection, don’t do it when speed is important. 

-30-

You may also like...