5

So this is the code which makes me sad :

private static void AssignId(object entity, string id)
        {
            var idFieldInfo = entity.GetType().GetProperties().SingleOrDefault(it => it.GetCustomAttributes(typeof(KeyAttribute), false).Any());
            if (idFieldInfo != null)
            {
                var type = idFieldInfo.PropertyType;

                if (type == typeof(byte))
                {
                    idFieldInfo.SetValue(entity, Convert.ToByte(id), null);
                }
                else if (type == typeof(short))
                {
                    idFieldInfo.SetValue(entity, Convert.ToInt16(id), null);
                }
                else if (type == typeof(int))
                {
                    idFieldInfo.SetValue(entity, Convert.ToInt32(id), null);
                }
                else if (type == typeof(long))
                {
                    idFieldInfo.SetValue(entity, Convert.ToInt64(id), null);
                }
                else if (type == typeof(sbyte))
                {
                    idFieldInfo.SetValue(entity, Convert.ToSByte(id), null);
                }
                else if (type == typeof(ushort))
                {
                    idFieldInfo.SetValue(entity, Convert.ToUInt16(id), null);
                }
                else if (type == typeof(uint))
                {
                    idFieldInfo.SetValue(entity, Convert.ToUInt32(id), null);
                }
                else if (type == typeof(ulong))
                {
                    idFieldInfo.SetValue(entity, Convert.ToUInt64(id), null);
                }
            }
        }

Is there a smarter way to assign a string value corresponding integer

v00d00
  • 3,215
  • 3
  • 32
  • 43
  • 1
    Check out [this article](http://www.codeproject.com/Articles/61460/Using-LINQ-for-type-conversion), it covers a wider range of target types than `ChangeType`, but you would parse the string your string yourself. – Sergey Kalinichenko Apr 27 '12 at 09:52
  • Possible duplicate of [Setting a property by reflection with a string value](https://stackoverflow.com/questions/1089123/setting-a-property-by-reflection-with-a-string-value) – Alena Kastsiukavets Jul 24 '17 at 11:50

1 Answers1

10

You can use Convert.ChangeType

if (idFieldInfo != null)
{
     var type = idFieldInfo.PropertyType;
     idFieldInfo.SetValue(entity, Convert.ChangeType(id, type), null);
}
L.B
  • 114,136
  • 19
  • 178
  • 224