Click here to Skip to main content
Click here to Skip to main content

Tagged as

Get Anonymous Object Properties using Inferred Casting

, 3 Apr 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Ever wonder how to get at the Properties of an Anonymous Object without Reflection? If you know the data Types of the properties, here is an Extension to the Object object that allows you to do just that: public static T InferCasting(this object o, T example) { ...
Ever wonder how to get at the Properties of an Anonymous Object without Reflection? If you know the data Types of the properties, here is an Extension to the Object object that allows you to do just that:
 
       public static T InferCasting<T>(this object o, T example)
       {
           return (T)o;
       }
 
For example:
 
Suppose you have an anonymous object stored in the Tag of a WinForm TreeNode. Now an event fires and passes the node to you, and you can 'see' the Tag but you need to get at the Anonymous properties.
 
Here's how the Object extension comes into play, allowing you to 'infer' the casting by sending example properties to the extension method:
 
object o = ((object)((TreeNode)sender).Tag);
var v = o.InferCasting(new { level = "", mode = "", item = "", accept = "" });    //extended method on Object
// and now....
string mode = v.mode;
string item = v.item;
string method = v.accept;
 
In this case the property types were all string, but could just as easily have been any type - just pass the correct type in the example.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Greg Burman
Software Developer Serexx Ltd.
Canada Canada
In '97 or so I started fiddling around with this new thing called the Internet. Mistake.
 
I blinked and found myself in 2000 ditching my Accounting designation and starting to write code for a living - mostly ASP Classic back then along with some C++ and a little assembler, PHP, Perl/CGI (ouch) and of course Javascript and most of the other web-side tools.
 
With v3.0 .Net finally became something I couldn't ignore and so here I am still coding - WinForm, ADO, SQL, .Net, and WPF shortly, no doubt to be followed by Silverlight and maybe some MVC.
 
"Teach me, learn or get out of the way."

Comments and Discussions

 
GeneralReason for my vote of 1 absolutelly useless Pinmemberjason_999923-Nov-10 3:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150129.1 | Last Updated 3 Apr 2010
Article Copyright 2010 by Greg Burman
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid