469,312 Members | 2,524 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,312 developers. It's quick & easy.

C# cast to anonymous type

2
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'?
Aug 22 '09 #1
4 9216
tlhintoq
3,525 Expert 2GB
just guessing but have you tried...

(var)al[0].field1

or

var Recovered = (var)al[0];
Console.WriteLine(Recovered.field1);
Aug 22 '09 #2
venil7
2
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
Aug 22 '09 #3
Plater
7,872 Expert 4TB
Why did you need to do all that work instead of just type-casting?
Aug 25 '09 #4
Yeah, at that rate, introspection is straightforward enough.

You should be able to do something like:

f = a.GetType().GetProperty("field1").GetValue(a);
Oct 1 '14 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

7 posts views Thread by James Mcguire | last post: by
3 posts views Thread by Harry Keck | last post: by
5 posts views Thread by Nick Flandry | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Geralt96 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.