How to dynamically add Properties in C# .NET?

There are certain situations where we have to create object dynamically with properties added to the object dynamically. Data related to these properties may be coming in from external sources like a file or from any other serialized format. We can achieve this with the help of reflection, but it is bit complex and should have some prior knowledge of Reflection.

What is meant by Dynamic Creation of Properties in c#?


Dynamic creation of properties means at the time of writing the code, programmer is not aware of the properties which can be part of the object and its value. For Example there may be some data which needs to be read from say xml file, In this case there should be some organized way by which we can represent the data, This can be in the form of a object.

Content of this object and the properties cannot be deduced while writing the application, it needs to be constructed from the xml file which is read when the application runs.

Expando Object


Expando Object comes to the rescue in this case, It represents a dynamic object where the properties can be added to the object dynamically. Since it implements IDictionary interface, it stores the properties and associated value as Key-Value Pairs.

Given below is an example using Expando Object where properties are added to it dynamically.

Here i have defined the properties and its metadata as a list of PropertyInfo objects including the type information of the properties.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeGen
{
    class PropInfo
    {
        public string PropertyName { get; set; }

        public string PropertyValue { get; set; }

        public Type PropertyType { get; set; }
        
        public PropInfo(string propName,string propValue,Type type)
        {
            PropertyName = propName;
            PropertyValue = propValue;
            PropertyType = type;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var propertiesInfo = new List<PropInfo>() {
               new PropInfo("Author","Mary",typeof(string)),
               new PropInfo("Revision","1",typeof(int)),
               new PropInfo("Description","This is a book",typeof(string)),
               new PropInfo("Cost","23.90",typeof(float)),
            };

            //Creating the Dynamic Object and adding the Properties Dynamically with the Property and its type
            var book = new ExpandoObject() as IDictionary<string,object>;
            foreach (var item in propertiesInfo)
            {
                book[item.PropertyName] = Convert.ChangeType(item.PropertyValue, item.PropertyType);
            }

            dynamic bookExpando = book as ExpandoObject;

            //Let us try to access the Properties one by one with their value and type
            //Note: We can also access the members with the help of [] operator just like accessing Dictionary members
            Console.WriteLine($"{bookExpando.Author} : {bookExpando.Author.GetType()}");
            Console.WriteLine($"{bookExpando.Revision} : {bookExpando.Revision.GetType()}");
            Console.WriteLine($"{bookExpando.Description} : {bookExpando.Description.GetType()}");
            Console.WriteLine($"{bookExpando.Cost} : {bookExpando.Cost.GetType()}");

        }
    }
}

Output


After running the code above we will obtain the output indicating the content of each properties and its corresponding type as shown below:

How to dynamically add C# properties At Runtime. Expando Object

Here i have done type conversion of Expando Object as IDictionary so that we can add the properties dynamically.

Comments

Popular posts from this blog

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

Step By Step Guide to Detect Heap Corruption in Windows Easily