Add properties dynamically at run time in existing class c#

amethianil picture amethianil · May 19, 2017 · Viewed 19.3k times · Source

I have a UI from where we are adding following values in a table Fields

  • ProductName
  • ProductId
  • ProductCode

I have a existing class Product with some existing properties

public class Product
{
    public string ProductID { get; set; }
    //product in a product search listing
    public string StoreName { get; set; }
    public string SearchToken { get; set; }

}

I am looking for a method which will add properties in existing class Product at run time (dynamically) when user adds values in a table Fields

Answer

jason.kaisersmith picture jason.kaisersmith · May 19, 2017

I don't know a way of defining properties during runtime, but another possibiity for you to achieve what you need is to use a dynamic object in C# known as ExpandoObject.

You first need to declare your dynamic object, it uses a kind of Dictionary internally so you can then add your properties to it.

using System.Dynamic;
dynamic newobj = new ExpandoObject();

//I can add properties during compile time such as this
newobj.Test = "Yes";
newobj.JValue = 123;

//Or during runtime such as this (populated from two text boxes)
AddProperty(newobj, tbName.Text, tbValue.Text);

public void AddProperty(ExpandoObject expando, string name, object value)
{
    var exDict = expando as IDictionary<string, object>;
    if (exDict.ContainsKey(propertyName))
        exDict[propertyName] = propertyValue;
    else
    exDict.Add(propertyName, propertyValue);
}

I have used it once in a solution here: Flattern child/parent data with unknown number of columns

But these sources can probably explain it better; https://www.oreilly.com/learning/building-c-objects-dynamically

https://weblog.west-wind.com/posts/2012/feb/08/creating-a-dynamic-extensible-c-expando-object

https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/types/using-type-dynamic

But, I'm not sure that this would really offer you any real advantages over using a simple Dictionary<string, object>