Home > Programming, Software, Tech > Some Interesting Code – your thoughts required

Some Interesting Code – your thoughts required

Thursday, 18 August 2011 11:22 am

Without going to into a long story, I found some interesting code here to convert anonymous types to any strongly typed, well, type.

 

public static object ToType<T>(this object obj, T type)
{

    //create instance of T type object:
    var tmp = Activator.CreateInstance(Type.GetType(type.ToString())); 

    //loop through the properties of the object you want to covert:          
    foreach (PropertyInfo pi in obj.GetType().GetProperties()
    {
      try 
      {   

        //get the value of property and try 
        //to assign it to the property of T type object:
        tmp.GetType().GetProperty(pi.Name).SetValue(tmp, 
                                  pi.GetValue(obj, null), null)
      }
      catch { }
     }  

   //return the T type object:         
   return tmp; 
}

From this codeproject article.

Anyone have any thoughts on this?  Is it good? Bad? Inefficient? Crap??

Categories: Programming, Software, Tech
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: