Using the dynamic keyword to transfer anonymous types

If you have an anonymous type in c# and you want to transfer it to another method then you normally have to implement an concrete type and use this type.
If you have the following Linq query:

var result = dataTable.AsEnumerable().Join(
                dr => dr["FK_Kontinent"],
                dr => dr["PK_Kontinent"], 
                (drInner, drOuter) => 
                    new { Name = drInner["AnimalName"], Kontinent = drOuter["Kontinent"] }

The query returns an anonymous type with the properties Name and Kontinent. If you need this type in another Method you have to cast it to dynamic.

foreach (var item in result)

The PrintResult method takes an dynamic parameter and you can use the anonymous type in this method. (if you know the properties)

public static void PrintResult(dynamic result)
     Console.WriteLine(" {0} wohnt in {1} ", result.Name, result.Kontinent);

If you have a note or a question please write a comment.

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.