Showing posts with label anonymous type to object. Show all posts
Showing posts with label anonymous type to object. Show all posts

Sunday, April 24, 2011

Convert object into anonymous type C#

Firstly I want to tell you that to use anonymous types isn't best practice. I was thinking if we can parse anonymous type into object then object should be parsed into anonymous type too.

here's an example.
lets suppose, we create a list of object type and we add some items in it of a anonymous type.

List obj = new List();

obj.Add((object)new {Id=1, Name="S"});
obj.Add((object)new {Id=2, Name="N"});
obj.Add((object)new {Id=3, Name="NS"});



 In the above list, I have added three objects. How can I retrieve the Id and Name attribute. There are two possibilities one we can create a strongly typed class but that will waste the purpose of a Anonymous type and the other one is to use using Generics or Templates. I will create a small method that will convert object into Anonymous type and will be available for querying the data in the code... 
public static T ConvertObjectIntoAnonymousType(T object, T typeOfObject) {         
return (T)object; 
}
 How we will use this function. 
object o = obj[0]; 



var anonymousObject = ConvertObjectIntoAnonymousType(o, new {Id=0, Name=""}); 


Its been converted. What we did? We created a anonymous type in the second argument of the same as we have the list object type. This type will be hold in T of the function ConvertObjectIntoAnonymousType and will be able to cast object into type T that is anonymous type. Using this technique we can save the time to create classes. I used this technique when I was using deserializing the dataset's XML for querying data. Hope this would help to everyone.