Microsoft.Protocols.TestSuites.Common.Common.SetSpecifiedPropertyValueByName C# (CSharp) Method

SetSpecifiedPropertyValueByName() public static method

Set a value in the target object using the specified property name
public static SetSpecifiedPropertyValueByName ( object targetObject, string propertyName, object value ) : void
targetObject object The target object
propertyName string The property name
value object The property value
return void
        public static void SetSpecifiedPropertyValueByName(object targetObject, string propertyName, object value)
        {
            if (string.IsNullOrEmpty(propertyName) || null == value || null == targetObject)
            {
                return;
            }

            PropertyInfo matchedProperty = targetObject.GetType().GetProperty(propertyName);

            if (matchedProperty != null)
            {
                if (matchedProperty.PropertyType == typeof(DateTime?))
                {
                    value = DateTime.Parse(value.ToString());
                }
                else if (matchedProperty.PropertyType == typeof(byte) || matchedProperty.PropertyType == typeof(byte?))
                {
                    value = byte.Parse(value.ToString());
                }
                else if (matchedProperty.PropertyType == typeof(bool) || matchedProperty.PropertyType == typeof(bool?))
                {
                    if (value.ToString() == "0")
                    {
                        value = false;
                    }
                    else if (value.ToString() == "1")
                    {
                        value = true;
                    }
                    else
                    {
                        value = bool.Parse(value.ToString());
                    }
                }
                else if (matchedProperty.PropertyType == typeof(uint) || matchedProperty.PropertyType == typeof(uint?))
                {
                    value = uint.Parse(value.ToString());
                }
                else if (matchedProperty.PropertyType == typeof(int) || matchedProperty.PropertyType == typeof(int?))
                {
                    value = int.Parse(value.ToString());
                }
                else if (matchedProperty.PropertyType == typeof(ushort) || matchedProperty.PropertyType == typeof(ushort?))
                {
                    value = ushort.Parse(value.ToString());
                }

                matchedProperty.SetValue(targetObject, value, null);
            }
        }
Common