Posts Creating Your Own Custom Dynamic C# Classes
Post
Cancel

Creating Your Own Custom Dynamic C# Classes

the class:

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
//source - http://dontcodetired.com/blog/post/Creating-Your-Own-Custom-Dynamic-C-Classes
using System.Collections.Generic;
using System.Dynamic;
using System.Text;

namespace CustomDynamic
{
    class MyDynamicClass : DynamicObject
    {
        private readonly Dictionary<string, object> _dynamicProperties = new Dictionary<string, object>(); 

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            _dynamicProperties.Add(binder.Name, value);

            // additional error checking code omitted

            return true;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            return _dynamicProperties.TryGetValue(binder.Name, out result);
        }

        public override string ToString()
        {
            var sb = new StringBuilder();

            foreach (var property in _dynamicProperties)
            {
                sb.AppendLine($"Property '{property.Key}' = '{property.Value}'");
            }

            return sb.ToString();
        }
    }
}

use of :

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
//source - http://dontcodetired.com/blog/post/Creating-Your-Own-Custom-Dynamic-C-Classes
using System;

namespace CustomDynamic
{
    class Program
    {
        static void Main(string[] args)
        {            
            dynamic d = new MyDynamicClass();

            // Need to declare as dynamic, the following cause compilation errors:
            //      MyDynamicClass d = new MyDynamicClass();
            //      var d = new MyDynamicClass();

            // Dynamically add properties
            d.Name = "Sarah"; // TrySetMember called with binder.Name of "Name"
            d.Age = 42; // TrySetMember called with binder.Name of "Age"

            Console.WriteLine(d.Name); // TryGetMember called
            Console.WriteLine(d.Age); // TryGetMember called

            Console.ReadLine();
        }
    }
}

origin - http://www.pipiscrew.com/?p=5842 creating-your-own-custom-dynamic-c-classes

This post is licensed under CC BY 4.0 by the author.
Contents

Trending Tags