Posted by: advapi | July 19, 2008

Anonymous type in C# 3.0

While working on my project and I was doing a Select from DB using LINQ, here’s my query

var sql = from o1 in dataContext.AdsForDomains
where o1.IDDomain.Equals(IDDomain)
select new {o1.IDAdsDomain, o1.IDAds, o1.Container, o1.AD.Description, o1.AD.AdsSize, o1.AD.Merchant.Name};

I bounded then this to a GridView and started to working with the gridview behaviour… everything was fine since I needed to read the loaded value from the e.Row.DataItem…. my problem was… how do I read anonymous type value? If I binded a whole row of a table, I would have got the strongly typed object but in this case not…. googling around and doing some test I discovered that in c# 3.0 there’re some limitations about anonymous type (refer to this for better explanation).

He’re what I did, I used the “Cast” method to cast the object inside the e.Row.DataItem to the strongly type I passed to.

protected void gvwAdsForDomains_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
DropDownList ddl = e.Row.FindControl(“ddlContainer”) as DropDownList;
if (ddl != null)
{
var mytype = Cast(e.Row.DataItem,
new
{
IDAdsDomain = 0,
IDAds = 0,
Container = string.Empty,
Description = string.Empty,
AdsSize = new AdsSize(),
Name = string.Empty
});

ddl.SelectedValue = mytype.Container;
}
}
}

private T Cast<T>(object o, T type)
{
return (T)o;
}

In that way I was able to read the content of fields that where stored inside the anonymous type. I also tryied (with no luck) to get the fields by reflection. I’ll investigate more as soon as I’ll have time.

Hope it helps,

Bests

Advertisements

Responses

  1. Silverlight 2 (previously referred to as version 1.1)[22] includes a version of the .NET Framework, implementing the same full Common Language Runtime version as .NET Framework 3.0

    [wikipedia]

    Difatti son 5 mb di installer =)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: