Get value from anonymous type

Saeid picture Saeid · Mar 17, 2012 · Viewed 22.7k times · Source

I have a method as following:

public void MyMethod(object obj){

  // implement

}

And I call it like this:

MyMethod(new { myparam= "waoww"});

So how can I implement MyMethod() to get myparam value?

Edit

I use this:

dynamic d= obj; 
string param = d.myparam; 

but the error rise :

'object' does not contain a definition for 'myparam' 

also I use breakpoint and I see the d have myparam string property.

And is there any way to check dynamic type to if contain any property like this:

if(d.contain(myparam))?

Edit II

This is my main code:

public static MvcHtmlString SecureActionLink(this HtmlHelper htmlHelper, 
         string linkText, string actionName, string controllerName, 
         object routeValues, object htmlAttributes) {


    string areaName = 
         (string)htmlHelper.ViewContext.RouteData.DataTokens["area"];

        dynamic areaObject = routeValues;

        if(areaObject != null && !string.IsNullOrEmpty(areaObject.area))
            areaName = areaObject.area;

// more
}

and call it as:

<p>@Html.SecureActionLink("Secure Link between Areas", "Index", "Context", 
                          new { area = "Settings" }, null)</p>

And Error is:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a
 definition for 'area'

 Line 303:  dynamic areaObject = routeValues;
 Line 304:
 Line 305:  if(areaObject != null && !string.IsNullOrEmpty(areaObject.area))
 Line 306:      areaName = areaObject.area;
 Line 307:

 Source File: D:\Projects\MyProject\HtmlHelpers\LinkExtensions.cs    Line: 305 

Edit III

This is my AssemblyInfo of HtmlHelper definition:

[assembly: AssemblyTitle("MyProject.Presentation")]
[assembly: InternalsVisibleTo("cpanel.MyProject.dev")]

but there is an error yet: 'object' does not contain a definition for 'area' I use different assemblies but how can it possible, when I use breakpoint I can see that my dynamic areaobject have area name property and also I can see the value of that, but the error say: 'object' does not contain a definition for 'area' I can't figure it how it can be possible?

Edit

I change the assembly and now dynamic type is internal but the error remains as before

Answer

Saeid picture Saeid · Mar 18, 2012

Use this one:

string area = areaObject.GetType().GetProperty("area").GetValue(areaObject, null);