Some programming tasks require dynamic nature of properties exposed by an object. E.g. it might be needed to access object property by a given key, it might be needed to get all object properties and iterate over them. Dynamic properties are useful when you need to manage them at runtime, when your object is already instantiated.
In this article we are going to create simple implementation of dynamic properties using C# programming language. We’ll use generics for our dynamic properties to make the implementation more flexible and to avoid boxing operations when value types are used for underlying property values.
Assembly:T1.dll
Namespace:T1.Common
Using the code
1 2 3
MyClass c1 = new MyClass(); c1.Name = "123"; int i = c1.ID;
Using .NET Invoke Method
1 2 3 4 5
MyClass c1 = new MyClass(); PropertyInfo pi = c1.GetProperty("Name"); pi.SetValue(c1, "123"); pi = c1.GetProperty("ID"); int i = (int)pi.GetValue(c1, null);
Using DynamicProperty Method
1 2 3 4 5
MyClass c1 = new MyClass(); var setName = DynamicProperty.SetProperty("Name"); setName(c1, "123"); var getID = DynamicProperty.GetProperty("ID"); int i = getID(c1);
DynamicProperty Method is fast than Invoke Method.
If you want to clone the same object of class, you must inherit “ICloneable” interface and implement Clone() method for clone function. Now only through ValueHelper Class can be simple to complete this goal.
Assembly:T1.dll
Namespace:T1.Common
Using the code:
1 2 3 4 5 6 7
MyClass a = new MyClass(); a.Id = 123; a.Name = "abc"; MyClass b = new MyClass(); b.Id = a.Id; b.Name = a.Name; Console.WriteLine("b Id={0} Name={1}", b.Id, b.Name);
And the following code in the same
1 2 3 4 5 6
MyClass a = new MyClass(); a.Id = 123; a.Name = "abc"; MyClass b = new MyClass(); ValueHelper.CopyData(a, b); Console.WriteLine("b Id={0} Name={1}", b.Id, b.Name);
You can also use Property.GetValue/SetValue to achieve the same purpose, but ValueHelper.CopyData performance on faster than the Property.GetValue/SetValue.
ValueHelper Class copy only int/float/string… basic types of variables, do not copy the object type variable.
Therefore, the following code to try to copy the a.Item object will be skipped.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
class MyClass1 { public string ID{get; set;} }
class MyClass2 { public string Name{get; set;} public MyClass1 Item{get; set;} }
MyClass2 a = new MyClass2(); a.Name = "abc"; a.Item = new MyClass1(); a.ID = "123"; MyClass2 b = new MyClass2(); ValueHelper.CopyData(a, b); //b.Item will be null.