Some coworker said once "Every time you hear dynamic means a load of troubles is coming by". I didn't agree. I know lots of interesting stuff can only be done using Reflection and even Reflection.Emit. Just to give some context, you are talking about Microsoft Framework 4.0 and the new type dynamic type declaration.
- declare a variable as dynamic
- your first assignmenet to this variable defines the real type it will have
- the legal or illegal operations will be evaluated after this assignement
The classical problem is the "custom properties" issue. You have an business application but every customer wants its own set of extra properties and the requirements of the customer can overcome your worst scenarios/nighmares. You could go the Reflection.Emit way but that's really hard for most programers. Let's try the dynamic way.
using System; public class CustomProperty { #region Private Fields private string _name = String.Empty; private string _type = String.Empty; private dynamic _value; #endregion public string Name { get { return _name; } set { _name = value; } } public string Type { get { return _type; } set { _type = value; } } public dynamic Value { get { return _value; } set { _value = value; } } }
I suppose you will now read the CustomProperty definitions from some storage be it a database, XML file, it really does't matter.
private static Type GetDataType(string type) { Type propType = Type.GetType(type); if (propType == null) propType = Type.GetType("System." + type); if (propType == null) propType = Type.GetType("App.CustomProperties." + type); return propType; }
var customProperty = new CustomProperty(); customProperty.Name = prop.Name; customProperty.Type = prop.PropertyType.Name; Type targetType = GetDataType(customProperty.Type); if (targetType != null) { if (targetType.IsEnum) customProperty.Value = ConvertStringToEnum(targetType, ""); else if (targetType == typeof (Int16)) customProperty.Value = (Int16) 0; else if (targetType == typeof (Int32)) customProperty.Value = (Int32) 0; else if (targetType == typeof (Int64)) customProperty.Value = (Int64) 0; } else { customProperty.Value = " "; customProperty.Value = string.Empty; }
- there is no keyword to define the real type of a dynamic variable/field/property
- the real type is defined by the first assignement
- do this assignment as soon as you know the real type
- assign the actual value after the previous assignment