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).
Contributed by Sams Publishing Rating: / 1 November 16, 2009
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.4Adding a Behavior to an Anonymous Type
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection;
// 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.
The var keyword can be used to initialize the index of a for loop or the recipient object of a foreach loop. The former is a simple anonymous type and the latter becomes a useful construct when the container to iterate over is something more than a sample collection. Listing 1.5 shows a for statement, and Listing 1.6 shows the foreach statement, both using the var construct.
LISTING 1.5Demonstrating How to Iterate Over an Array of Integers—Using the Fibonacci Numbers from Listing 1.1—and the var Keyword to Initialize the Index
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace AnonymousForLoop { class Program { static void Main(string[] args) { var fibonacci = new int[]{ 1, 1, 2, 3, 5, 8, 13, 21 }; for( var i=0; i<fibonacci.Length; i++) Console.WriteLine(fibonacci[i]); Console.ReadLine(); } } }
LISTING 1.6Demonstrating Basically the Same Code but Using the More Convenient foreach Construct
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AnonymousForEachLoop { class Program { static void Main(string[] args) { var fibonacci = new int[]{ 1, 1, 2, 3, 5, 8, 13, 21 }; foreach( var fibo in fibonacci) Console.WriteLine(fibo); Console.ReadLine(); } } }
The only requirement that must be met for an object to be the iterand in a foreach statement is that it must functionally represent an object that implements IEnumerable or IEnumerable<T>—the generic equivalent. Incidentally, this is also the same requirement for bindability, as in binding to a GridView.
TIP
At any time, you can branch in for or foreach statements with the break or continue keywords or the goto, return, or throw statements.
An all-too-common use of the for construct is to copy a subset of elements from one collection of objects to a new collection, for example, copying all the customers in the 48843 ZIP code to a customersToCallOn collection. In C# 2.0, the yield return and yield break key phrases actually played this role. For example, yield return signaled the compiler to emit a state machine in MSIL—in essence, it emitted the copy collection for you.
In .NET 3.5, the ability to query collections, datasets, and XML to essentially ask questions about data or copy some elements is one of those things that LINQ does very well. Listing 1.7 shows code that uses a LINQ statement to return just the numbers in the Fibonacci short sequence that are divisible by 3. (For now, don’t worry about understanding all of the elements of the query.)
LISTING 1.7 A foreach Statement Whose Iterand Is Derived from a LINQ Query
using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace AnonymousForEachLoopFromExpression { class Program { static void Main(string[] args) { var fibonacci = new int[]{ 1, 1, 2, 3, 5, 8, 13, 21, 33, 54, 87 }; // uses LINQ query foreach( var fibo in from f in fibonacci where f%3==0 select f) Console.WriteLine(fibo); Console.ReadLine();
} } }
The LINQ query—used as the iterand in the foreach statement—makes up this part of the Listing 1.7:
from f in fibonacci where f % 3 == 0 select f
For now, it is enough to know that this query meets the requirement that it returns an enumerable result, in fact, IEnumerable<T> where T is anint type.
If this is your first experience with LINQ, the query might look strange. The capability and power and this book will quickly make them familiar and desirable friends. For now, it is enough to know that queries meet the requirement of an enumerable resultset and can be used in a foreach statement.
The using statement is shorthand notation for try...finally. With try...finally and using, the purpose is to ensure resources are cleaned up before the using block exits or the finally block is run. This is accomplished by calling Dispose, which implies that items created in using statements implement IDisposable. Employ using when the created types implement IDisposable—like SqlConnections—and use try...finally when you need to do some kind of cleanup work, but do not necessarily need to invoke Dispose (see Listing 1.8).
LISTING 1.8Using Statement and var Work Because SqlConnection Implements IDisposable
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient;
namespace AnonymousUsingStatement { class Program { static void Main(string[] args) { string connectionString = "Data Source=BUTLER;Initial Catalog=AdventureWorks2000;" + "Integrated Security=True"; using( var connection = new SqlConnection(connectionString)) { connection.Open(); Console.WriteLine(connection.State); Console.ReadLine();
} } } }
The help documentation will verify that SqlConnection is derived from DBConnection, which, in turn, implements IDisposable. You can use a tool like Anakrino or Reflector—free decompilers and disassemblers—to see that Dispose in DBConnection invokes the Close method on a connection.
To really understand how things are implemented, you can use ILDASM—or one of the previously mentioned decompilers—and look at the MSIL that is emitted. If you look at the code in Listing 1.8’s IL, you can clearly see the substitution of using for a properly configured try...finally block. (The try element—after SqlConnection creation—and the finally block invoking Dispose are shown in bold font in Listing 1.9.)
LISTING 1.9 The MSIL for the var and using Statement in Listing 1.8
You don’t have to master IL to use .NET effectively, but you can learn from it and writing .NET emitters—code that emits IL directly—is supported in the .NET Framework. As shown in the MSIL, you can infer, for example, that the proper way to use try...finally is to create the protected object, try to use it, and, finally, clean it up. If you read a little further—in the finally block starting with IL 0030—you can see that the compiler also put a check in to ensure that the protected object, the SqlConnection, is compared with null before Dispose is called. This code is demonstrated in IL 0030, IL 0031, IL 0032, and the branch statement on IL 0036.
Anonymous types can be returned from functions because the garbage collector (GC) cleans up any objects, but outside of the defining scope, the anonymous type is an instance of an object. Unfortunately, returning an object defeats the value of the IntelliSense system and the strongly typed nature of anonymous types. Although you could use reflection to rediscover the capabilities of the anonymous type, again you are taking a feature intended to make life more convenient and making it somewhat inconvenient again. Listing 1.10 puts these elements together, but as a practical matter, it is best to design solutions to use anonymous types within the defining scope. (Ironically, using objects within the defining scope was a style issue used in C++ to reduce the probability of memory leaks. Those familiar with C++ won’t find this slight quirk of anonymous types any more inconvenient.)
LISTING 1.10Returning an Anonymous Type from a Method Defeats the Strongly Typed Utility of Anonymous Types
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection;
namespace ReturnAnonymousTypeFromMethod { class Program { static void Main(string[] args) { var anon = GetAnonymous(); Type t = anon.GetType(); Console.WriteLine(t.GetProperty("Stock").GetValue(anon, null)); Console.ReadLine(); }
public static object GetAnonymous() { var stock = new {Stock="MSFT", Price="32.45"}; return stock; } } }
Although it is intellectually satisfying to play with the reflection subsystem, writing code like that in Listing 1.10 is a slow and painful means to an end. (In addition, the code in Listing 1.10, as written, is fraught with the potentiality for bugs due to null values being returned from GetType, GetProperty, and GetValue.)
Please check back tomorrow for the conclusion to this series.