Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically getting/setting a property of an object in C# 2005

Tags:

c#

reflection

I've inherited a code base and I'm writing a little tool to update a database for it. The code uses a data access layer like SubSonic (but it is home-grown). There are many properties of an object, like "id", "templateFROM" and "templateTO", but there are 50 of them.

On screen, I can't display all 50 properties each in their own textbox for data entry, so I have a listbox of all the possible properties, and one textbox for editing. When they choose a property in the listbox, I fill the textbox with the value that property corresponds to. Then I need to update the property after they are done editing.

Right now I'm using 2 huge switch case statements. This seems stupid to me. Is there a way to dynamically tell C# what property I want to set or get? Maybe like:

entObj."templateFROM" = _sVal;

??

like image 349
Matt Dawdy Avatar asked Dec 10 '22 21:12

Matt Dawdy


2 Answers

You need to use System.Reflection for that task.

entObj.GetType().GetProperty("templateFROM").SetValue(entObj, _sVal, null);

This should help you.

like image 134
okutane Avatar answered Feb 15 '23 09:02

okutane


What you want is called reflection.

like image 26
Thomas Avatar answered Feb 15 '23 10:02

Thomas