I have a UI from where we are adding following values in a table Fields
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
This is all of the code which is needed to add a new property to an existing Type . Type propertyType = typeof(string); string propertyName = "Notes"; string fieldName = $"_{propertyName.
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject. sampleMember instead of more complex syntax like sampleObject.
Dynamic objects expose members such as properties and methods at run time, instead of at compile time. This enables you to create objects to work with structures that do not match a static type or format.
1.2 Basic Dynamic Properties and Their Significance Theoretically, it can be defined as the ratio of stress to strain resulting from an oscillatory load applied under tensile, shear, or compression mode.
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 propertyName, object propertyValue)
{
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With