Welcome to EMC Consulting Blogs Sign in | Join | Help

Anthony Steele's Blog

C#3 anonymous types as parameters

Over the holidays, for some light holiday reading while resting the bruises from ski-slope related activities, I took Bill Wagner's book "More effective C#" it showed a few ways in which C#3's anonymous types can be passed to methods, which i had thought was beyond thier scope.

 Given this definition:

var anonTypedObject = new { Name = "Fred", Balance = 12 };

All we can say about it is that it's descended from Object, so it can be passed to a method ike this:

static void ShowTypeOfObject(Object obj)
{
  
Console.WriteLine("(O) Type is " + obj.GetType().ToString() + " value is " + obj.ToString());
}

 ShowTypeOfObject(anonTypedObject) produces output of:

(O) Type is <>f__AnonymousType0`2[System.String,System.Int32] value is { Name = Fred, Balance = 12 }
 

This also shows that that the generated anonymous type is itself a kind of generic tuple.

 However strongly-typed methods can also accept the anonymous type, if the method is generic. This version works much the same:

static void ShowTypeGeneric<T>(T t)
{
   
Console.WriteLine("(G) Type is " + t.GetType().ToString() + " value is " + t.ToString());
}

ShowTypeGeneric(anonTypedObject); 

But what useful work can a generic method do on an anonymous type? The generic method has to make sense for any type from object on down, so it knows little useful about the type. But it can also be passed a function to apply to the data, which does know what to do with the anonymous type. If it's an anonymous function, of course. In a more complex example the generic method might check nulls or iterate a list as well as applying the worker method, but here's a very simple example:

static void ShowFuncOutput<T>(Func<T, string> func, T data)
{
   
Console.WriteLine(func(data));
}

ShowFuncOutput(v => "Lambda: Value is " + v.ToString(), anonTypedObject);

 Which produces output as you might expect;

Lambda: Value is { Name = Fred, Balance = 12 }

Though if it gets much more complex than this, I would recommend paying the cost of a non-anonymous type, it's likely to be worth it in the long run.

Published Monday, January 05, 2009 10:43 AM by Anthony.Steele

Comments

No Comments
Anonymous comments are disabled

About Anthony.Steele

Programmer in c# for Conchango

This Blog

Syndication

Powered by Community Server (Personal Edition), by Telligent Systems