Looking for a way to pass an associative array to a method. I’m looking to rewrite an Actionscript tween package in C# but running into trouble with ‘associative’ arrays/objects. Normally in Actionscript I might do something like:
public function tween(obj:DisplayObject, params:Object = null):void { if (params.ease != null) { //do something } //... }
And this could be called like:
tween(this, {ease:'out', duration:15});
I’m looking for a way to do the same in C#. So far, I’ve gathered my options to be:
a) creating a class or struct to define the possible param keys and types and pass that
b) pass the parameters as generic type
tween(frameworkElement, new {ease = 'out', duration = 15});
assuming
public static void tween(FrameworkElement target, object parameters);
and figure out some way to use that in the tween function (I’m not sure how to separate the key=value’s given that object. any ideas?)
c) create a Dictionary<string, object> to pass the parameters into the tween function
Any other ideas or sample code? I’m new to C#.
Edit
Took me all day to figure this out:
‘Anonymous types cannot be shared across assembly boundaries. The compiler ensures that there is at most one anonymous type for a given sequence of property name/type pairs within each assembly. To pass structures between assemblies you will need to properly define them.’
EDIT: This is basically the mechanism that HtmlHelper extensions use in ASP.NET MVC. It’s not original with me.
I’d favor a hybrid approach that has two different signatures. Note: I haven’t tried this and there may be a conflict between the two signatures so you may have to give the second method a slightly different name to allow the compiler to choose between them, but I don’t think so.
Then you have a ParameterDictionary class that uses reflection on the anonymous type and sets up the dictionary.
This gives you both ease of use and ease of consumption — the ‘ugly’ reflection stuff is wrapped up in the single constructor for the dictionary rather than in your method. And, of course, the dictionary can be used over and over for similar purposes with the reflection code only written once.