Click here to Skip to main content
15,861,172 members
Articles / Programming Languages / C#
Tip/Trick

Get Anonymous Object Properties using Inferred Casting

Rate me:
Please Sign up or sign in to vote.
3.67/5 (3 votes)
3 Apr 2010CPOL 11.2K   1   1
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:

C#
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:

C#
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)


Written By
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 Pin
Jason Ti23-Nov-10 2:27
Jason Ti23-Nov-10 2:27 
Reason for my vote of 1
absolutelly useless

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

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