ergunysr
ergunysr

Reputation: 291

Is it possible to set a dynamically created property name from database in c#?

As I asked at title,

Is it possible to set a dynamically created property name from database or from an external value in C#?

If yes then how?

Upvotes: 1

Views: 239

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564333

Typically, the best way to handle this is to store the value within a Dictionary<string, object> (or even Dictionary<string, dynamic>, or some other class as a value). This provides you a way to use a "dynamic property name" (the key) along with a value.

While a custom DynamicObject will allow you to add dynamic members at runtime based on an external source, using those properties becomes problematic, as you don't know how to refer to them from your code.

EDIT: code example:

Dictionary<string, object> myValues = new Dictionary<string, object>();
myValues.Add("FieldName", "valueFromDatabase");
//to get value back
object val = myValues["FieldName"];
//or if not sure value exists
if (myValues.TryGetValue("FieldName", out val))
{
    //do something with val
}    

Upvotes: 2

Related Questions