I have moved!

I've moved my blog
CLICK HERE
Showing posts with label wish. Show all posts
Showing posts with label wish. Show all posts

Thursday, 13 November 2008

Chain – a LINQ operator for dealing with Linked Lists

I don’t think there’s anything in LINQ that will do this, though I expect I’m wrong - I have a tendency to write my own extension method to do something and then discover that LINQ already provides a general version of it. But in the mean time, here’s my Chain method:

public static IEnumerable<T> Chain<T>(this T first, Func<T, T> follow) where T : class
{
    for (T item = first; item != null; item = follow(item))
        yield return item;
}

It’s designed to be used in any situation where a traditional linked list exists. I used it in my AutoDisposal library to get a list of all the types inherited by a given type. It chains a bunch of objects together into an enumerable list by following links between them.

The irritation that provoked this minor burst of creativity is that if you use the GetFields method of Type, there doesn’t seem to be a simple way to get all the instance fields in that type, including inherited ones. By default, GetFields does include inherited fields, but only public ones. To get all public and non-public instance fields, including all inherited ones, you have to walk the chain of base types and get the fields declared in each type. So you’d better use BindingFlags.DeclaredOnly, or you’ll end up with duplicates of the public fields.

I wanted to write a LINQ expression that would get me a single flat list of all the fields in a type, so this is how I used Chain as part of it:

instance.GetType()
    .Chain(type => type.BaseType)
    .SelectMany(type => type.GetFields(BindingFlags.Instance | 
                                       BindingFlags.Public | 
                                       BindingFlags.NonPublic | 
                                       BindingFlags.DeclaredOnly))
    

In this case, the BaseType property of Type is the “next item” pointer in the linked list I’m interested in, but to use LINQ effectively we need it in the form of an IEnumerable<Type>, and so Chain provides a nifty way to do that.

Shouldn’t something like Chain be in the BCL (if it isn’t already?)

Friday, 22 August 2008

Observable Property Pattern

Is there something like this in the standard libraries? And if not, why not?

public class Observable<T>
{
    private T _value;

    public class ChangedEventArgs : EventArgs
    {
        public T OldValue { get; set; }
        public T NewValue { get; set; }
    }

    public EventHandler<ChangedEventArgs> Changed;

    public T Value
    {
        get { return _value; }

        set
        {
            if (!value.Equals(_value))
            {
                T oldValue = _value;
                _value = value;

                EventHandler<ChangedEventArgs> handler = Changed;
                if (handler != null)
                    handler(this, new ChangedEventArgs
                                  {
                                      OldValue = oldValue, 
                                      NewValue = value
                                  });
            }
        }
    }
}

That is, the observable property pattern as a reusable class.

This should be in the System namespace for all to enjoy. It's a great thing when what used to be a "pattern" can now be captured in code using language features (the enabling feature in this case being generics, obviously).

Thursday, 22 May 2008

Virtual Properties in C#

It is an important and popular fact that properties in C# can be defined in interfaces. For example:

public interface IThing
{
    IThing Parent { get; }
}

We can then implement that interface on a concrete class:

public class : Thing
{
    public IThing Parent 
    { 
        get { /* return a parent from somewhere */ }
    }
}

Like so. We can also use the nifty new syntax to implement the property to be just like a simple field:

public IThing Parent { get; set; }

Notice (this is the crucial point) that this defines a setter as well as a getter for the property. It doesn't make any difference to clients of IThing, because they only need a getter, but it might be useful for clients of Thing. Very nice.

Now I know what you're thinking. Nobody British writes a blog post like this about a language feature unless some aspect of it is unsatisfactory. So here it comes.

Suppose I want to follow the same pattern but using an abstract class instead of an interface. It's basically the same idea:

public abstract class IThing
{
    public abstract IThing Parent { get; }
}

The only difference in the concrete derived class is the need to use the modifier override:

public class Thing : IThing
{
    public override IThing Parent
    {
        get { /* blah */ }
    }
}

But there's another difference, can you guess it?

public class Thing : IThing
{
    public override IThing Parent { get; set; }
}

The above produces an error: cannot override because 'IThing.Parent' does not have an overridable set accessor.

It's the same if you try to write the getter and setter in long hand. You are banned from providing a setter, even though it makes no difference to the correctness of your implementation of IThing.

I can just hear the language designers saying wisely to themselves, "Why the heck would anyone ever want to override the getter but not the setter, or vice versa for that matter?" Well, now you know, you crazy old language designers.

If the base class has an abstract getter but no setter (or vice versa) it ought to be a perfectly valid thing to override that getter (or setter) while also providing a non-virtual matching setter (or getter).

To fix this, we need the ability to apply the override modifier on the getter and setter individually.

Friday, 30 November 2007

A new use for the C# using keyword

It worries me that the using keyword doesn't have enough meanings already! But coming from a C++ background I'm very keen on the using (...) { scope } syntactic sugar. It helps with clients of IDisposable objects. But so far, it provides no help for implementors. So my suggestion is to allow the using keyword to act as a modifier on member variables.

Simple example:

class B { using FussyResource X; } 

is equivalent to:

class B : IDisposable 
{
  FussyResource X;

  public virtual void Dispose()
  {
    if (X != null)
      X.Dispose();  
  }
} 

So we can compose objects hierarchically and the IDisposable pattern is followed automatically through the hierarchy.

The using keyword in this context indicates that the outer object owns the inner object, determining its lifetime. Applying the using keyword to a type that does not implement IDisposable is an error. Of course inheritance needs to work too:

class C : B { } 

already works, because C inherits B's implementation of IDisposable. But consider:

class D : B {  using FussyResource Y; }

This needs to be translated as:

class D : B 
{
  FussyResource Y;

  public override void Dispose()
  {
    if (Y != null)
      Y.Dispose();

    base.Dispose();
  }
}

This need to override the base class's Dispose means that the base class must have a virtual Dispose. If it doesn't, then the user will not be able to take advantage of the using field modifier when they inherit from that base class.

Finally, to allow it to freely mix with existing code or to allow custom disposal in advanced cases, we also need work well alongside explicit declarations of IDisposable in the same class:

class E : IDisposable 
{
  using FussyResource X;
  IntPtr Win32Resource Y;

  public void Dispose()
  {
    Win32Helpers.FreeWin32Resource(Y);
  }
}

produces:

class E : IDisposable
{
  FussyResource X;
  IntPtr Win32Resource Y;

  public virtual void Dispose()
  {
    __Custom_Dispose();

    if (X != null)
      X.Dispose();
  }

  private void __Custom_Dispose()
  {
     Win32Helpers.FreeWin32Resource(Y);
  }
}

This could be added to C# as a pure language feature, requiring no changes to the CLR. It fits in with the existing use of using as defining a scope control the lifetime of objects. It gives C# support for implementing the IDisposable pattern that is on a par with C++/CLR. And it would mean that most of the time, writing IDisposable.Dispose by hand would be unnecessary. A little more procedural code is moved into a simple declaration.