Search This Blog

Friday, December 5, 2014

Dynamic Object Runtime C# Example

C# > Sytem.Dynamic > DynamicObject

DynamicObject specifies dynamic behavior at run time.






Example:

Create dynamic object in runtime.

Dynamically Add C# Properties at Runtime.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication26
{
    public class MyDynamicObject : DynamicObject
    {
        Dictionary<string, object> dictionary = new Dictionary<string, object>();
        public object this[string propertyName]
        {
            get
            {
                return dictionary[propertyName];
            }
            set
            {
                dictionary[propertyName] = value;
            }
        }
        public override bool TryGetMember(
            GetMemberBinder binder, out object result)
        {
            return dictionary.TryGetValue(binder.Name, out result);
        }
        public override bool TrySetMember(
            SetMemberBinder binder, object value)
        {
            dictionary[binder.Name] = value;
            return true;
        }
      
        public override bool TrySetIndex(
            SetIndexBinder binder, object[] indexes, object value)
        {
            int index = (int)indexes[0];
            if (dictionary.ContainsKey("Property" + index))
                dictionary["Property" + index] = value;
            else
                dictionary.Add("Property" + index, value);
            return true;
        }
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dynamic obj = new MyDynamicObject();
            obj["column1"] = 1;
            obj.column2 = 2;

            var v1 = obj["column1"];
            var v2 = obj.column2;
        }
    }
}