A Closer Look at Anonymous Types
(Page 1 of 4 )
In this second part of a three-part series on anonymous types, we'll increase our understanding of them by adding methods, returning anonymous types from functions, and more. This article is excerpted from chapter one of
LINQ Unleashed, written by Paul Kimmel (Sams, 2008; ISBN: 0672329832).
Adding Methods to Anonymous Types
To really understand language possibilities, it’s helpful to bend and twist a language to make it do things it might not have been intended to do directly. One of these things is adding behaviors (aka methods). Although it might be harder to find a practical use for anonymous type–behaviors, Listing 1.4 shows you how to add a behavior to and use that behavior with an anonymous type. (The generic delegate Func in bold in the listing is used to initial the anonymous type’s method.)
LISTING 1.4 Adding a Behavior to an Anonymous Type
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace AnonysmousTypeWithMethod
{
class Program
{
static void Main(string[] args)
{
// adding method possibility
Func<string, string, string> Concat1 =
delegate(string first, string last)
{
return last + ", " + first;
};
// whacky method but works
Func<Type, Object, string> Concat2 =
delegate(Type t, Object o)
{
PropertyInfo[] info = t.GetProperties();
return (string)info[1].GetValue(o, null) +
", " + (string)info[0].GetValue(o, null);
};
var dena = new {First="Dena", Last="Swanson", Concat=Concat1};
//var dena = new {First="Dena", Last="Swanson", Concat=Concat2};
Console.WriteLine(dena.Concat(dena.First, dena.Last));
//Console.WriteLine(dena.Concat(dena.GetType(), dena));
Console.ReadLine();
}
}
}
The technique consists of defining an anonymous delegate and assigning that anonymous delegate to the generic Func class. In the example, Concat was defined as an anonymous delegate that accepts two strings, concatenates them, and returns a string. You can assign that delegate to a variable defined as an instance of Func that has the three string parameter types. Finally, you assign the variable Concat to a member declarator in the anonymous type definition (referring to var dena = new {First="Dena", Last="Swanson", Concat=Concat}; now).
After the plumbing is in place, you can use IntelliSense to see that the behavior—Concat—is, in fact, part of the anonymous type dena, and you can invoke it in the usual manner.
Next: Using Anonymous Type Indexes in For Statements >>
More Database Articles
More By Sams Publishing