Posts
49
Comments
83
Trackbacks
0
February 2008 Entries
Lambda Expression type inference doesn't quite work on actual methods

One of the nice things with lambda expression is type inference - it is actually pretty neat.  A neat example that is as follows:

private void Test()

{

   string original = "Muljadi";

   string upper = Demo(original, s => s.ToUpper());

   int length = Demo(original, s => s.Length);

}

 

private static TResult Demo<T, TResult>(T value, Func<T, TResult> func)

{

   return func(value);

}

In the example above, the first call to the Demo method has first parameter being a string - which then is immediately inferred to type T.  The compiler will also then infer that the second parameter is a lambda expression, which expects a single parameter, also of type T (which it has recognized as a string), walks thru the lambda expression and recognizes that it returns also a string.  As such, it determines that the first Demo method call will return a string and infer TResult as string.

The second call to the Demo method follows the same path, and again when parsing the lambda expression, it will determine that it returns string.Length, which is of type int - it will then infer TResult as int.

However, I found out that the type inference doesn't work as nicely with actual methods.  The snippet below wouldn't work - I tried with as many combinations as possible, and I could not get it to work without actually creating an instance of the delegate.

private void Test()

{

   string original = "Muljadi";

   int length = Demo(original, GetLength); // Type can't be inferred error

   length = Demo<string, int>(original, GetLength);

   length = Demo(original, new Func<string, int>(GetLength));

   length = Demo(original, s => GetLength(s));

}

 

private int GetLength(string s)

{

   return s.Length;

}

In my mind it just doesn't seem to make sense - the GetLength method is non-generic, has the return types and parameter type in the method and the compiler can't make sense of it.  The other 3 calls are valid because:

  1. You specify the type in the Demo method call itself
  2. Your instantiate the method as a Func delegate, where you also specify the types
  3. You actually make it as a lambda expression call
In the end, lambda expressions actually has better inference support than actual methods.  Hopefully Microsoft can add this in .NET 4.0.
posted @ Wednesday, February 13, 2008 6:47 PM | Feedback (0)
Expensive Home theatre...

One of my hobby / passion is home theaters, and even though $6 million is overkill, I thought I would brought it up as a good read Kipnis Studio Standard, 4096x2160 video, 18 ft screen, 8 speakers with 8 subs...

The Sony Quad HD projector is one of interest to me - it costs $100K (if this post is to be believed) with NO lens (another $19K option give or take a couple of grand given what kind of lens you want), but I would like to see how an 8 megapixel image would look like on a big screen.

Of course, the article doesn't talk about black level, contrast level, etc., but the equipment list is enough to make my mouth water.  My current ideal HT setup would be a Sony G90 with DynAudio Contour speakers (Velodyne subs), driven with some nice amps (Mark Levinson, Krell, Plinius, etc.).  Most probably by the time I can afford these, my wife would insist on a small (read: digital) PJ, so current choices for me would be either JVC RS-1/RS-2 (with a scaler that can do color control) or a Sony Diamond.

Perchance to dream...

posted @ Monday, February 11, 2008 9:45 AM | Feedback (0)
My foray into Lambda Expressions

I was aware of lambda expressions because I was reading about them in the C# 3.0 white paper specification, along with other new language features like extension methods, anonymous types, basis for LINQ, etc.  I thought it was cool enough, it makes passing anonymous delegates much better in terms of code writing/reading.  However, actually using them takes a bit of getting used to.  As such, I'd like to give a short example as to how I visualize writing lambda expressions.

Consider the following class structure representing a sports organization:

public class League

{

   private List<Conference> _conferences;

 

   public IList<Conference> Conferences

   {

      get { return _conferences; }

   }

}

 

public class Conference

{

   private List<Division> _divisions;

 

   public IList<Division> Divisions

   {

      get { return _divisions; }

   }

}

 

public class Division

{

   private List<Team> _teams;

 

   public IList<Team> Teams

   {

      get { return _teams; }

   }

}

 

public class Team

{

   private string _name;

 

   public string Name

   {

      get { return _name; }

   }

}

Basically, we have a League, which has a collection Conferences, which in turn have a collection of Divisions and each division having the Teams belonging to that division.  Let's say the task is to go collecting the names of all teams in the league - the code to do that is simple, you just loop through the conferences, loop through the division and then loop through the teams.  The code to do so will look like the following:

List<string> teamNames = new List<string>();

League league = new League();

 

foreach (Conference conference in league.Conferences)

{

   if (conference == null)

      continue;

 

   foreach (Division division in conference.Divisions)

   {

      if (division == null)

         continue;

 

      foreach (Team team in division.Teams)

      {

         if (team == null)

            continue;

 

         teamNames.Add(team.Name);        

      }

   }

}

The code above, it works, but it just seems mundane - you have multiple foreach loops, multiple null checks - it would be nice if we can refactor this somewhat.  So, we can create a method to refactor this - basically the method needs to be able to loop through a collection, check for null, and also do something else to the item being iterated.  In the code above, it needs to basically iterate through the inner collection twice (one for division and one for team), and when iterating through teams, it needs to add the team name to the collection (not iterate through).  With that pattern, a refactored method can be written as follows:

private void ForEach<T>(IEnumerable<T> enumerable, Action<T> action )

{

   if (enumerable == null)

      return;

 

   foreach (T item in enumerable)

   {

      action(item);

   }

}

The method above will basically take an enumerable, checks to make sure it can enumerate it, and then loop through that enumerable and do something to the item being iterated - these 3 things satisfy the condition of the refactored method as mentioned above.  Now, that something that needs to be done is defined by the Action<T> delegate that the consumer of this function needs to specify.  So the above foreach loops can be written (using anonymouse delegates) as follows:

ForEach(league.Conferences, delegate(Conference conf)

{

   ForEach(conf.Divisions, delegate(Division div)

   {

      ForEach(div.Teams, delegate(Team team)

      { teamNames.Add(team.Name); });

   });

});

Well... it looks OK, but it's fairly unreadable - not to mention the developer needs to make sure everything ends properly, especially with the combination of the curly braces and the parentheses.  Enters Lamda expression, and the above code becomes like this instead:

ForEach(league.Conferences,

   conf => ForEach(conf.Divisions,

      div => ForEach(div.Teams,

         team => { if (team != null) teamNames.Add(team.Name); })));

Now, it is more compact, no question about it.  However, is it more readable?  Given the above example, assuming the developer knows what needs to be expected, it may be more readable.  6 months from now if I were walking through the code, I would imagine it would take me awhile to read through that line - it requires knowing what the ForEach method does, it requires the developer to understood what the lambda expression is doing at each level, and it will be very hard to customize if the need arises.

That said, I have to say I learned quite a bit from trying to refactor the above code into lambda expressions - it gives me a better understanding as to how to use them, how to refactor methods as lambda expressions, and also shows me a glimpse as to how they can be dangerous.  Most probably, I would make the last piece of logic (collecting the team name) to be its own function and pass that as a delegate, instead of writing the delegate in-line.  Two reasons for that:

  1. It's the portion where most probably will require logic changes (say not to add the team name if team name is empty, or has spaces, etc.)
  2. It limits the consumer code to read like calling functions, so as I read through the code, I can understand it calls another piece of code (method) and I don't have to read the function definition in-line.

The above example is also a bit advanced since we're refactoring multiple foreach loops into a recursive delegate calls - take some time to make it sink through - it took me a good 2 hours to go through this the first time around.

posted @ Monday, February 11, 2008 9:16 AM | Feedback (2)
New delegates in .NET Framework 3.5

In the way distant past, I ended up creating a new delegate for just about each function I need represented as a delegate.  And as I experienced an explosion of delegates and needing to come up with the names for it, I ended up creating 2 sets of delegates as follows:

 

public delegate void VoidFunction();

public delegate void VoidFunction<T>(T argument1);

public delegate void VoidFunction<T, U>(T argument1, U argument2);

 

public delegate R Function<R>();

public delegate R Function<R, T>(T argument1);

public delegate R Function<R, T, U>(T argument1, U argument2);

My code will use the VoidFunction delegate to represent methods that doesn't return anything (void).  And I'll use the other one that needs return value - the type inference in .NET is nice since it strong types return values as well.  I also overload to 2 only since those are the ones I use most - I found that if I need one with more arguments, I'd better off creating a new delegate altogether since naming those delegates properly help in reading code.

With .NET 3.5, to support LINQ, Microsoft has created these same delegates set, but with more overloads so it can accept more parameters.  The delegates that return void are named Action, and the delegates that supply a return value are named Func.  Each has generic overloads to accept up to 4 parameters.  More information can be found here - you need to scroll all the way down to where you can see the list of delegates - there you'll see the Action delegates and the Func delegates.

A couple of snags:

  • Since the delegates are defined in .NET 3.5, that means that you need the 3.5 framework installed and your app need to also target the 3.5 framework.
  • The Func delegates put the return value last - in terms of usage, it doesn't matter since .NET will resolve it - but I'm finding this pattern a bit against their typical pattern of keeping the order of things the same.  Which is why in my implementation, I keep the return value type parameter as the first type.

I'm also suprised that Microsoft only started doing these now, instead of say since .NET 2.0, or even 3.0.  The only delegate that was created before (as early as 2.0 actually) was the Action<T> - since it is used for one of the method in List<T>, the ForEach method in particular.

posted @ Friday, February 08, 2008 12:19 PM | Feedback (1)
Disposing CollectionView (Detaching your data and the CollectionView)

One of my prior post talks about how CollectionView (and anything deriving from it like ListCollectionView) doesn't get garbage collected after use - even worse it continues to hang onto the data it was bound to, which may cause performance issues.  After fiddling through this, I found 3 ways to disconnect them, which I'll detail below.

- Derive classes from CollectionView that can dispose itself.

The subscriber to the CollectionChanged event is a protected function named 'OnCollectionChanged' - so the code is fairly trivial as shown below:

public class CollectionViewEx : CollectionView, IDisposable

{

   public CollectionViewEx(IEnumerable enumerable)

      : base(enumerable)

   {

   }

 

   ~CollectionViewEx()

   {

      Dispose(false);

   }

 

   #region IDisposable Members

 

   public void Dispose()

   {

      Dispose(true);

   }

 

   private bool _disposed = false;

   protected virtual void Dispose(bool disposing)

   {

      if (_disposed == false)

      {

         if (disposing)

         {

            // Dispose managed resources

            INotifyCollectionChanged ncc = SourceCollection as INotifyCollectionChanged;

            if (ncc != null)  // Unsubscribe from CollectionChanged event

               ncc.CollectionChanged -= this.OnCollectionChanged;

         }

 

         // Dispose unmanaged resource

         _disposed = true;

      }

   }

 

   #endregion

}

I'm using the Dispose Finalize pattern but left out suppressing Finalize so I can break through the code and verify that the garbage collector hits the finalizer.  New classes however also means that you have to create a new class for each type of CollectionView that you want to use.  Even worse, you can't use it with CollectionViewSource.GetDefaultView() since that method will return one of the .NET classes, but not yours.

- Create a collection class that can remove the CollectionChanged subscriber

public interface IRemoveCollectionChangedSubscriber

{

   bool RemoveCollectionChangedSubscriber(object subscriber);

}

 

public class MyObservableCollection<T> : ObservableCollection<T>,

   IRemoveCollectionChangedSubscriber

{

   public override event NotifyCollectionChangedEventHandler CollectionChanged;

 

   #region IRemoveCollectionChangedSubscriber Members

 

   public bool RemoveCollectionChangedSubscriber(object subscriber)

   {

      NotifyCollectionChangedEventHandler _event = CollectionChanged;

      if (_event == null)  // No subscriber

         return false;

 

      // Go through handler

      foreach (NotifyCollectionChangedEventHandler handler in _event.GetInvocationList())

      {

         if (object.ReferenceEquals(handler.Target, subscriber))

         {

            CollectionChanged -= handler;

            return true;

         }

      }

 

      return false;

   }

 

   #endregion

}

It is fairly simple code, I decided to create an interface that defines a method that can remove a subscriber, that way I can use the same interface in any other collection classes.  However, this also meant that I can't use the typical collection classes as is - I have to derive from it.  The consumer code is fairly simple; the consumer code is being called to remove the subscriber when a view is closed.

protected override void OnClosed(EventArgs e)

{

   base.OnClosed(e);

   DetachCollectionAndView(_someCollectionView);

}

 

private bool DetachCollectionAndView(CollectionView cv)

{

   IRemoveCollectionChangedSubscriber remover = cv.SourceCollection as IRemoveCollectionChangedSubscriber;

   return (remover != null) ? remover.RemoveCollectionChangedSubscriber(cv) : false;

}

Since the subsciber is the collection view itself, I pass the CollectionView object to the method.

- Use reflections

private bool DetachCollectionAndView(CollectionView cv)

{

   INotifyCollectionChanged ncc = cv.SourceCollection as INotifyCollectionChanged;

   if (ncc == null)

      return false;

 

   // Get the method that subscribes to OnCollectionChanged

   MethodInfo mi = cv.GetType().GetMethod("OnCollectionChanged",

      BindingFlags.NonPublic | BindingFlags.Instance, null,

      new Type[] { typeof(object), typeof(NotifyCollectionChangedEventArgs) },

      null);

   NotifyCollectionChangedEventHandler handler = (NotifyCollectionChangedEventHandler)

      Delegate.CreateDelegate(typeof(NotifyCollectionChangedEventHandler), cv, mi);

   collection.CollectionChanged -= handler;

 

   return true;

}

We know that the subscriber method is named 'OnCollectionChanged', it is protected, so we can search for this.  That function has an overload, so we have to provide the types used in the method to get the proper one using reflection.  Once we get it, then we create a delegate out of it and remove it out from the event by using the -= operator.  This approach is actually very straightforward, but it uses reflections, which people may want to avoid.  However, this approach requires the least amount of coding - you can still use the CollectionView class (or any of its derived classes), use WPF constructs that will return those classes, and also use any collection/list classes that you already use.

All in all, none of these would be necessary, if only Microsoft has implemented IDisposable in the CollectionView class, or even just provide a method to detach the collection.

posted @ Thursday, February 07, 2008 6:08 PM | Feedback (0)
Advantage in creating a base non-generic class

In the project I'm working in, we use generics a lot - I mean a LOT!  Most of the classes we create are also generic types - it provides some niceties that way.  As the classes grew, eventually I got to a point where I want to put in a static function that doesn't deal with the generic type, something like below: 

public abstract class Container<T>

{

   private T _content;

 

   public T Content

   {

      get { return _content; }

      set { _content = value; }

   }

 

   public static void SomeStaticFunctionNotInvolvingT()

   {

      // Code here, but doesn't refer to T

   }

}

Unfortunately, I can't call the static function elegantly; I have to provide a type, before I can access it.  I can access it like this: Container<int>.SomeStaticFunctionNotInvolvingT(); - but it's a bit like cheating, and if/when the type parameter has constraints, it gets weird too since I have to use a type that can work.  So, the other possible solutions:

  1. Use a different class - this is the easy one, but sometimes you might just happen to have a proper named class (which happens to be generic), so you just want to put it there
  2. Create a non-generic base class as the parent of your generic class and put the method there.  This approach is also more inline with better class design - you only put the stuff that is needed where it is needed (no need to put a method that doesn't refer to T in a generic class)

I chose to pursue the second approach, and even though it works, I can't help but try to justify why I should do this - what advantage does this give me.  Looking back at my knowledge on how methods are shared in memory, only the data gets changed, I thought that if I use the method in the generic class, the method can't be shared - since each instance of that generic class for each type will result in a new copy being created in memory - at least for struct types.  .NET seem to imply that for object types, the framework will just create one for type object and use it all over.  How can I prove this?

So, I created a test function to see if that static function points to the same delegate (function pointer) or not as follows:

public abstract class Container

{

   public static void NonGenericBaseClassStaticFunction()

   {

      // Code here - no T reference at all (doesn't even know about T)

   }

}

 

public delegate void VoidFunction();

private void CompareDelegates()

{

   VoidFunction d1 = Container<int>.SomeStaticFunctionNotInvolvingT;

   VoidFunction d2 = Container<float>.SomeStaticFunctionNotInvolvingT;

 

   bool b = d1.Equals(d2);  // false

 

   VoidFunction d3 = Container<Window>.SomeStaticFunctionNotInvolvingT;

   VoidFunction d4 = Container<Button>.SomeStaticFunctionNotInvolvingT;

 

   b = d3.Equals(d4);  // false

 

   VoidFunction d5 = Container<int>.NonGenericBaseClassStaticFunction;

   VoidFunction d6 = Container<float>.NonGenericBaseClassStaticFunction;

 

   b = d5.Equals(d6);  // true

 

   VoidFunction d7 = Container<Window>.NonGenericBaseClassStaticFunction;

   VoidFunction d8 = Container<Button>.NonGenericBaseClassStaticFunction;

 

   b = d7.Equals(d8);  // true

   // Best way to invoke

   Container.NonGenericBaseClassStaticFunction();

}

The Container class above becomes the base class of the above Container<T> class.  If you run the test code, the first 2 Equals check will yield false, since even though it is a static function, the actual function pointer will differ.  The last 2 however, will yield true, since they're accessing the same actual function defined in the base class.  As a bonus, I can call the static function without specifying the generic type.

All in all, the above approach has some nice benefits:

  1. Cleaner class design - you put the function that you need where you need it.  Why put a function that doesn't need the generic type in a generic class?
  2. Invoking it from outside looks more normal, since you don't need to specify any type
  3. Better memory footprint - this is a bit debatable, but if you instantiate a lot of instances of the generic class with different types, each one will result in a different method pointer to the static method.  It is optimized somewhat, but by using the base class implementation, you don't have that overhead at all, since all references to that static method will now positively go to a single method location.
posted @ Tuesday, February 05, 2008 6:38 PM | Feedback (0)
News