Connecting Tech Pros Worldwide Help | Site Map

C# cast to anonymous type

Newbie
 
Join Date: Aug 2009
Posts: 2
#1: Aug 22 '09
consider the following code:

Expand|Select|Wrap|Line Numbers
  1. var test1 = new { field1 = "hello" };
  2. ArrayList al = new ArrayList();
  3. al.Add(test1);
  4.  
  5. //compile error
  6. Console.WriteLine(al[0].field1);
  7.  
an anonymous type is created than placed into ArrayList.
al[0] obviously returns Object, how to cast this back to anonymous type to retrieve value of 'field1'?
tlhintoq's Avatar
Moderator
 
Join Date: Mar 2008
Location: Arizona, USA
Posts: 1,745
#2: Aug 22 '09

re: C# cast to anonymous type


just guessing but have you tried...

(var)al[0].field1

or

var Recovered = (var)al[0];
Console.WriteLine(Recovered.field1);
Newbie
 
Join Date: Aug 2009
Posts: 2
#3: Aug 22 '09

re: C# cast to anonymous type


ok, I found the answer:

first we need an Extension class:

Expand|Select|Wrap|Line Numbers
  1. static class Extension
  2.     {
  3.         static public T CastTo<T>(this object o, T t)
  4.         {
  5.             return (T)o;
  6.         }
  7.     }
which will add CastTo method to all Objects, then

Expand|Select|Wrap|Line Numbers
  1. var v = al[0];
  2. Console.WriteLine(v.CastTo(new { field1=String.Empty}).field1);
the trick is to pass an anonymous object to CastTo which has same signature as the one that we put to ArrayList
Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,148
#4: Aug 25 '09

re: C# cast to anonymous type


Why did you need to do all that work instead of just type-casting?
Reply

Tags
anonymous, c #, cast, type


Similar .NET Framework bytes