Friday, July 08, 2005

Great use for nested classes

When I first read about nested classes I thought it was just one of those obscure parts of c# that I was never likely to find a decent use for, but today I found quite a good use for it, and it was sitting right there in my previous post.

Usually we use a custom control to contain an UltraGrid like so


public class MyControl : UserControl
{
...

private UltraGrid myGrid;
}


In my last post I offered a solution to adding record headers to an UltraGrid, but I passed the RowHeaders in as a List parameter to the constructor, now in the problem I'm trying to solve, this list is already maintained by the user control, so it means I have to maintain in 2 separate places..... Well not any more


public class MyControl : UserControl
{
...
private list myRowNames;
private UltraGrid myGrid;

private class RowSelectorDrawFilter : IUIElementDrawFilter
{
private RowSelectorDrawFilter(MyControl control)
{
myControl = control;
}
...
private MyControl myControl;
}
}


Then at the business end of things in DrawElement I use the following

...
drawParams.DrawString(drawParams.Element.Rect, myControl.myRowNames[row.ListIndex], false, false);
...


This means that I can let the user control maintain the row names and no-one ever needs to know about our RowSelectorDrawFilter class as it's happily nested in MyControlClass.

1 comment:

  1. Anonymous9:05 am

    Scott,
    Why is the nested class needed? Can't the usercontrol just implement the interface and have it work, or is there some reason the usercontrol can't implement the interface? I tried it that way and it didn't work and I'm wondering why.

    Rob

    ReplyDelete